我会尽量保持简单,希望您能有所帮助。
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.
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/