一只划船的猪 2025-02-13 17:06 采纳率: 0%
浏览 27

electron自定义标题栏同时拖动和双击的功能搞定了吗

你好,electron自定义标题栏同时拖动和双击的功能搞定了吗,怎么搞的

  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2025-02-13 17:06
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    electron自定义标题栏同时拖动和双击的功能搞定了吗

    electron 中可以使用 webFrame.setNativeWindowOpenHandler 方法来实现自定义标题栏的拖动和双击功能。

    首先,需要在 main 函数中创建一个 BrowserWindow 对象,并设置 titleBarStyle 属性为 custom

    const { BrowserWindow } = require('electron');
    
    let win;
    
    function createWindow() {
      win = new BrowserWindow({
        width: 800,
        height: 600,
        titleBarStyle: 'custom',
        webPreferences: {
          nodeIntegration: true
        }
      });
    
      win.loadURL(`file://${__dirname}/index.html`);
    
      win.on('closed', () => {
        win = null;
      });
    }
    

    然后,在 index.html 文件中,使用 document.addEventListener 方法来监听标题栏的拖动和双击事件:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Custom Title Bar</title>
      </head>
      <body>
        <div id="title-bar" style="background-color: #333; color: #fff; padding: 10px; cursor: move;">
          <span id="title-text">Custom Title Bar</span>
        </div>
        <script>
          document.addEventListener('mousedown', (e) => {
            if (e.target.id === 'title-bar') {
              // 拖动标题栏
              document.body.style.cursor = 'move';
              document.addEventListener('mousemove', (e) => {
                // 获取标题栏的位置
                const titleBarRect = document.getElementById('title-bar').getBoundingClientRect();
                // 获取鼠标的位置
                const mousePosition = { x: e.clientX, y: e.clientY };
                // 计算标题栏的新位置
                const newX = mousePosition.x - titleBarRect.left;
                const newY = mousePosition.y - titleBarRect.top;
                // 设置标题栏的新位置
                document.getElementById('title-bar').style.top = `${newY}px`;
                document.getElementById('title-bar').style.left = `${newX}px`;
              });
              document.addEventListener('mouseup', () => {
                document.body.style.cursor = '';
                document.removeEventListener('mousemove', null, false);
              });
            }
          });
    
          document.addEventListener('dblclick', (e) => {
            if (e.target.id === 'title-bar') {
              // 双击标题栏
              console.log('Double click title bar');
            }
          });
        </script>
      </body>
    </html>
    

    在上面的代码中,我们使用 document.addEventListener 方法来监听标题栏的拖动和双击事件。拖动事件中,我们获取标题栏的位置和鼠标的位置,然后计算标题栏的新位置并设置标题栏的新位置。双击事件中,我们 simply log a message to the console。

    这样,electron 应用程序中就可以实现自定义标题栏的拖动和双击功能了。

    评论

报告相同问题?

问题事件

  • 创建了问题 2月13日