可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am hoping to track the position of the mouse cursor, periodically every t mseconds. So essentially, when a page loads - this tracker should start and for (say) every 100 ms, I should get the new value of posX and posY and print it out in the form.
I tried the following code - but the values do not get refreshed - only the initial values of posX and posY show up in the form boxes. Any ideas on how I can get this up and running ?
Track Mouse
回答1:
The mouse's position is reported on the event object received by a handler for the mousemove event, which you can attach to the window (the event bubbles):
(function() { document.onmousemove = handleMouseMove; function handleMouseMove(event) { var dot, eventDoc, doc, body, pageX, pageY; event = event || window.event; // IE-ism // If pageX/Y aren't available and clientX/Y are, // calculate pageX/Y - logic taken from jQuery. // (This is to support old IE) if (event.pageX == null && event.clientX != null) { eventDoc = (event.target && event.target.ownerDocument) || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0 ); } // Use event.pageX / event.pageY here } })();
(Note that the body of that if will only run on old IE.)
Example of the above in action - it draws dots as you drag your mouse over the page. (Tested on IE8, IE11, Firefox 30, Chrome 38.)
If you really need a timer-based solution, you combine this with some state variables:
(function() { var mousePos; document.onmousemove = handleMouseMove; setInterval(getMousePosition, 100); // setInterval repeats every X ms function handleMouseMove(event) { var dot, eventDoc, doc, body, pageX, pageY; event = event || window.event; // IE-ism // If pageX/Y aren't available and clientX/Y are, // calculate pageX/Y - logic taken from jQuery. // (This is to support old IE) if (event.pageX == null && event.clientX != null) { eventDoc = (event.target && event.target.ownerDocument) || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0 ); } mousePos = { x: event.pageX, y: event.pageY }; } function getMousePosition() { var pos = mousePos; if (!pos) { // We haven't seen any movement yet } else { // Use pos.x and pos.y } } })();
As far as I'm aware, you can't get the mouse position without having seen an event, something which this answer to another Stack Overflow question seems to confirm.
Side note: If you're going to do something every 100ms (10 times/second), try to keep the actual processing you do in that function very, very limited. That's a lot of work for the browser, particularly older Microsoft ones. Yes, on modern computers it doesn't seem like much, but there is a lot going on in browsers... So for example, you might keep track of the last position you processed and bail from the handler immediately if the position hasn't changed.
回答2:
Here's a solution, based on jQuery and a mouse event listener (which is far better than a regular polling) on the body:
$("body").mousemove(function(e) { document.Form1.posx.value = e.pageX; document.Form1.posy.value = e.pageY; })
回答3:
onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}
Open your console (Ctrl+Shift+J), copy-paste the code above and move your mouse on browser window.
回答4:
I believe that we are overthinking this,
function mouse_position(e) { //do stuff }
回答5:
What I think that he only wants to know the X/Y positions of cursor than why answer is that complicated.
// Getting 'Info' div in js hands var info = document.getElementById('info'); // Creating function that will tell the position of cursor // PageX and PageY will getting position values and show them in P function tellPos(p){ info.innerHTML = 'Position X : ' + p.pageX + '
Position Y : ' + p.pageY; } addEventListener('mousemove', tellPos, false);
* { padding: 0: margin: 0; /*transition: 0.2s all ease;*/ } #info { position: absolute; top: 10px; right: 10px; background-color: black; color: white; padding: 25px 50px; }
回答6:
Irrespective of the browser, below lines worked for me to fetch correct mouse position.
event.clientX - event.currentTarget.getBoundingClientRect().left event.clientY - event.currentTarget.getBoundingClientRect().top
回答7:
ES6 based code:
let handleMousemove = (event) => { console.log(`mouse position: ${event.x}:${event.y}`); }; document.addEventListener('mousemove', handleMousemove);
If you need throttling for mousemoving, use this:
let handleMousemove = (event) => { console.warn(`${event.x}:${event.y}\n`); }; let throttle = (func, delay) => { let prev = Date.now() - delay; return (...args) => { let current = Date.now(); if (current - prev >= delay) { prev = current; func.apply(null, args); } } }; // let's handle mousemoving every 500ms only document.addEventListener('mousemove', throttle(handleMousemove, 500));
here is example