如何使用 JavaScript 获取鼠标位置?

发布于 2024-09-14 04:46:06 字数 479 浏览 3 评论 0原文

我想通过 JavaScript 获取鼠标 xy 坐标。我尝试了 pageXpageYclientXclientY,但没有显示任何内容。我已经在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若能看破又如何 2024-09-21 04:46:06

是的 - 您还需要将该函数连接为事件处理程序。

您的事件应该带有一个事件参数:

function mouseDown(event) {

然后您需要告诉浏览器在事件发生时调用您的函数:

document.onmousedown = mouseDown;

Yes - you also need to hook the function up as an event handler.

Your event should take an event parameter:

function mouseDown(event) {

And then you need to tell the browser to call your function when the event occurs:

document.onmousedown = mouseDown;
岁月静好 2024-09-21 04:46:06

它不起作用,因为您没有监听任何事件。当任何鼠标事件发生时,您需要传递此函数。尝试下面的代码.. 获取单击位置

function getPos(evt) {
 evt = event || window.event;
 return {x:evt.clientX,y:evt.clientY};
}

现在您可以在事件侦听器中调用此函数,如下所示。

addEventListener( 'click' , function(event) {
  var mousex = getPos(event).x;
  Var mousex = getPos(event).y;

  alert(mousex);alert(mousey);
});

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

function getPos(evt) {
 evt = event || window.event;
 return {x:evt.clientX,y:evt.clientY};
}

Now you can just call this function inside an event listener like this.

addEventListener( 'click' , function(event) {
  var mousex = getPos(event).x;
  Var mousex = getPos(event).y;

  alert(mousex);alert(mousey);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文