简体   繁体   中英

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

event.pageY gets the mouse position relative to the entire document height ( document.documentElement.offsetHeight I assume).

But how do I get the mouse position relative to the current viewport, which is 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).

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

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

I was in similar situation, I required cursor's coordinates wrt the Viewport (since my page was scrollable).

I tried other answers here, they didn't seem to work once the screen was scrolled (they worked well with non-scrollable pages).

Upon reading a few documentation page of https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent I found that while working with scrollable page, if you need X and Y coordinates wrt the current Viewport (ie even if scrolled), it would be better to use event.pageX instead.

var pageX = MouseEvent.pageX;

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX

Here is a code example:

document.addEventListener('mousemove', event => {
    console.log(event.clientY) // THIS should do what you want     
})

Click the snippet below to see it in action:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM