javascript - Electronjs 拖放

标签 javascript drag-and-drop electron

我是 Electron 新手,想处理拖放功能。
想要删除文件并获取其扩展名。根据扩展名更改屏幕上的某些内容。

即,如果将 .mp3 文件放入其中,则希望将 backgroundColor 更改为绿色,并将 .jpg 文件更改为红色。

我已经设法使用拖放,但不知道如何正确处理它。到目前为止,我的代码是:
main.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
  </head>
  <body style="color: grey;">
    <div class="character">
      <h1>{nome}</h1>
      <img id="char_anim" src="assets/goku.gif" />
    </div>
  </body>
  <a href="#" id="drag">item</a>
  <script type="text/javascript" charset="utf-8">
    document.getElementById("drag").ondragstart = (event) => {
      event.preventDefault();
      ipcRenderer.send("ondragstart", "/path/to/item");

    };
  </script>
</html>

main.js

const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");

const MAIN_HTML = path.join("file://", __dirname, "main.html");
const CHILD_PADDING = 50;

const onAppReady = function () {
  let parent = new BrowserWindow({
    width: 800,
    height: 1200,
    transparent: false,
    frame: true,
  });

  parent.once("close", () => {
    parent = null;
  });

  parent.loadURL(MAIN_HTML);
};

//~ app.on('ready', onAppReady);
app.on("ready", () => setTimeout(onAppReady, 500));

// dragndrop
ipcMain.on("ondragstart", (event, filePath) => {
  event.sender.startDrag({
    file: filePath,
    icon: "/path/to/icon.png",
  });
});

我可以解释更多,但我只需要一种方法来处理应用程序,以了解哪个扩展程序有这个删除的文件并为一个或另一个显示不同的消息。

最佳答案

在您的主进程中,您可以使用 path 获取文件扩展名模块:

let ext = require('path').extname(filePath)

然后,您可以将返回值发送到渲染器,如下所示:
event.sender.send('get-file-extension', ext);

之后,您可以使用 ipcRenderer 获取发送的值以更改背景颜色:
ipcRenderer.on('get-file-extension', (event, extension) => {
     if(extension == '.mp3')
          document.body.style.backgroundColor = "green";
     else if(extension == '.jpg')
          document.body.style.backgroundColor = "red";
});

关于javascript - Electronjs 拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61173494/

相关文章:

javascript - 如何正确使用Jquery模糊功能

javascript - 如何克隆不同颜色的 div block ?

node.js - Electron Node 异步调用未调用

objective-c - 为什么我可以在 NSWindowController 中实现 NSDraggingDestination 方法?

json - 在Mac Catalyst中运行的iOS应用程序中的DropInteraction中接收JSON文件

usb - 通过 USB 使用 Electron

c# - 与 C#/Mono 后端配合良好的跨平台 UI 模块

javascript - vue.js http 获取 web api url 渲染列表

javascript - 在 JavaScript 中切换文本

javascript - 页面清除 - JQuery Mobile