[英]How to get the position of an iframe relative to the top window's viewport?
[英]How to get the mouse position relative to the window viewport in javascript?
event.pageY
获取鼠标 position 相对于整个文档高度(我假设document.documentElement.offsetHeight
)。
但是如何获得相对于当前视口的鼠标 position ,即document.documentElement.clientHeight
?
For example, if the browser window size has a 720 pixel height, I scroll down 3 pages and keep the mouse in the middle of the window, the position should be "360", not 1800 (720 x 3 - 720 / 2).
尝试使用event.clientY
应该始终返回正确的值,而不管滚动
我处于类似情况,我需要光标在视口中的坐标(因为我的页面是可滚动的)。
我在这里尝试了其他答案,一旦滚动屏幕,它们似乎就不起作用(它们适用于不可滚动的页面)。
在阅读了https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent的一些文档页面后,我发现在使用可滚动页面时,如果您需要当前视口的 X 和 Y 坐标(即即使滚动),最好使用event.pageX
代替。
var pageX = MouseEvent.pageX;
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX
这是一个代码示例:
document.addEventListener('mousemove', event => {
console.log(event.clientY) // THIS should do what you want
})
单击下面的代码段以查看它的实际效果:
document.addEventListener('mousemove', e => { document.getElementById('log').innerHTML = ` Relative to screen:<br> e.screenX: <b>${e.screenX}</b><br> e.screenY: <b>${e.screenY}</b><br><br> Relative to viewport:<br> e.clientX: <b>${e.clientX}</b><br> e.clientY: <b>${e.clientY}</b>` })
<div id='log'></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.