javascript - 如何确保 mousemove 仅适用于窗口而不适用于内部 DOM 元素?

标签 javascript

我会尽量保持简单,希望您能有所帮助。

  var el1 = document.getElementById('el1');
  var el2 = document.getElementById('el2');
  window.addEventListener('mousemove',function(e){
    var mouseX = e.offsetX;
    var mouseY = e.offsetY;
    var x = (mouseX + el1.offsetLeft) / 50;
    var y = (mouseY + el2.offsetTop) / 50;
    el1.style.transform = "translateX("+ x +"px) translateY("+ y +"px)";
    el2.style.transform = "translateX("+ x +"px) translateY("+ y +"px)";
  });

用于视差效果的简单函数,但它会在 window 内的每个 dom 元素上触发。 因此,当它命中内部 DOM 元素时,el1/el2 会根据触发的mouseover 捕捉到新位置。

如何确保 mousemove 在窗口上工作,而不是在 window 的内部元素上工作?

重要说明:我无法应用 pointer-events:none; 因为内部元素具有需要使用的 href 标记。

感谢您的帮助。

谢谢

最佳答案

offsetX/offsetY指相对于鼠标当前所在元素的位置。

The offsetX read-only property of the MouseEvent interface provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.

您可能正在寻找clientX/clientY :

The clientX read-only property of the MouseEvent interface provides the horizontal coordinate within the application's client area at which the event occurred (as opposed to the coordinates within the page). For example, clicking in the top-left corner of the client area will always result in a mouse event with a clientX value of 0, regardless of whether the page is scrolled horizontally. Originally, this property was defined as a long integer.

关于javascript - 如何确保 mousemove 仅适用于窗口而不适用于内部 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918737/

相关文章:

javascript - 确保随机分配的属性没有重复

javascript - 检测是否加载了 Underscore.js

使用 Switch 语句的 JavaScript - 未获得预期输出

php - 使用 html 和 JavaScript 的表单创建测验

javascript - 使用appendTo()时,点击事件不会绑定(bind)到动态元素

javascript - 在 JavaScript 中插入属性

javascript - 根据特定时区生成规则

javascript - 关于jquery ajax,php文件已运行但成功功能不起作用

javascript - P5.js - 填充颜色为 'n %'

javascript - 如何计算点击事件时嵌套元素相对于其父元素的位置