Javascript 如何在javascript中获取相对于窗口视口的鼠标位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14717617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:44:07  来源:igfitidea点击:

How to get the mouse position relative to the window viewport in javascript?

javascriptjavascript-eventsheightviewport

提问by nice ass

event.pageYgets you the mouse position relative to the entire document height(document.documentElement.offsetHeightI assume).

event.pageY让您获得相对于整个文档高度的鼠标位置(document.documentElement.offsetHeight我假设)。

But how do I get the mouse position relative to the current viewport, which is document.documentElement.clientHeight?

但是我如何获得相对于当前视口的鼠标位置,这是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).

例如,如果浏览器窗口大小为 720 像素高度,我向下滚动 3 页并将鼠标保持在窗口中间,则位置应为“360”,而不是 1800 (720 x 3 - 720 / 2)。

回答by lostsource

Try using event.clientYthat should always return the correct value regardless of scrolling

尝试使用event.clientY它应该始终返回正确的值,而不管滚动

https://developer.mozilla.org/en-US/docs/DOM/event.clientY

https://developer.mozilla.org/en-US/docs/DOM/event.clientY

回答by Bergi

Use event.clientYto get the mouse positionrelative to the browser viewport (Compatibility table).

使用event.clientY来获取鼠标位置相对于浏览器窗口(兼容性表)。