如何使用 JavaScript 获取鼠标位置?
我想通过 JavaScript 获取鼠标 x 和 y 坐标。我尝试了 pageX、pageY、clientX、clientY,但没有显示任何内容。我已经在 IE 和 Firefox 上测试过了。
在以下事件中我做错了什么吗?
var x=0;
var y=0;
function mouseDown(){
alert("This is displayed");
evt=event||window.event;
alert(evt.clientX);
alert(evt.clientY);
alert(evt.pageX);
alert(evt.pagey);
alert("Flow doesn't reach here...");
}
I want to get mouse x and y co-ordinates through JavaScript. I have tried pageX, pageY, clientX, clientY, but nothing is displayed. I have tested this on both IE and Firefox.
Is there something I'm doing wrong in the following event?
var x=0;
var y=0;
function mouseDown(){
alert("This is displayed");
evt=event||window.event;
alert(evt.clientX);
alert(evt.clientY);
alert(evt.pageX);
alert(evt.pagey);
alert("Flow doesn't reach here...");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的 - 您还需要将该函数连接为事件处理程序。
您的事件应该带有一个事件参数:
然后您需要告诉浏览器在事件发生时调用您的函数:
Yes - you also need to hook the function up as an event handler.
Your event should take an event parameter:
And then you need to tell the browser to call your function when the event occurs:
它不起作用,因为您没有监听任何事件。当任何鼠标事件发生时,您需要传递此函数。尝试下面的代码.. 获取单击位置
现在您可以在事件侦听器中调用此函数,如下所示。
It's not working because you are not listening for any events. You need to pass this function when any mouse events occur. Try my code below.. gets position on click
Now you can just call this function inside an event listener like this.