如何避免 `click` 和 `mousedown` 事件之间的冲突

Genie

你好!为了避免 clickmousedown 事件之间的冲突,可以通过检查拖拽的状态来决定是否应触发 click 事件。我们可以设置一个简单的延迟,并使用一个标志位来确定是否应该忽略 click 事件。

下面是修改后的代码:

<script>
    const { remote, ipcRenderer } = require('electron');
    const ball = document.getElementById('ball');

    let isDragging = false;
    let ignoreClick = false;

    ball.addEventListener('mousedown', (e) => {
        isDragging = true;
        ignoreClick = false; // 重置 click 忽略标志

        // 设置一个延迟,如果在此期间未发生 mouseup,则认为是拖动
        setTimeout(() => {
            if (isDragging) {
                ignoreClick = true;
            }
        }, 200); // 延迟时间可以根据需要调整
    });

    document.addEventListener('mousemove', (e) => {
        if (isDragging) {
            const [mouseX, mouseY] = [e.screenX, e.screenY];
            ipcRenderer.send('float-ball-move', { x: mouseX - 25, y: mouseY - 25 });
        }
    });

    document.addEventListener('mouseup', () => {
        isDragging = false;
    });

    ball.addEventListener('click', (e) => {
        if (ignoreClick) {
            return; // 忽略拖动时触发的 click 事件
        }

        if (ball.style.backgroundColor === 'red') {
            ball.style.backgroundColor = 'green';
            ipcRenderer.send('toggle-state', 'green');
        } else {
            ball.style.backgroundColor = 'red';
            ipcRenderer.send('toggle-state', 'red');
        }
    });
</script>

要点总结:

  1. 使用一个 ignoreClick 标志来决定是否处理 click 事件。
  2. mousedown 事件中重置该标志,并设置定时器,以便在一段时间后更新 ignoreClick 状态。
  3. 如果在这段时间内发生了足够的移动(即正在拖动),则会设置 ignoreClicktrue,从而忽略随后的 click 事件。

希望这样能帮你解决问题!如果有任何其他问题,请随时告诉我。

posted @ 2024-06-24 10:41  西门飘柔  阅读(490)  评论(0)    收藏  举报