javascript 在鼠标单击时获取 x 和 y 坐标 [英] javascript get x and y coordinates on mouse click

查看:20
本文介绍了javascript 在鼠标单击时获取 x 和 y 坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的 div 标签,当我单击它时(onClick 事件),它将运行 printMousePos() 函数.这是 HTML 标签:

I have a little div tag that when I click it (onClick event), it will run the printMousePos() function. This is the HTML tags:

<html>
    <header>
        <!-- By the way, this is not the actual html file, just a generic example. -->
        <script src='game.js'></script>
    </header>
    <body>
        <div id="example">
            <p id="test">x: , y:</p>
        </div>
    </body>
</html>

这是一个单独的 .js 文件中的 printMousePos 函数:

This is the printMousePos function in a seperate .js file:

function printMousePos() {
    var cursorX;
    var cursorY;
    document.onmousemove = function(e){
    cursorX = e.pageX;
    cursorY = e.pageY;
}
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

是的,该函数确实有效(当您单击它时它知道),但它对 x 和 y 返回 undefined,所以我假设函数中的获取 x 和 y 代码不正确.有任何想法吗?我也知道 javascript 本身没有任何内置函数来返回 x 和 y 就像在 java 中一样,例如 .. 有没有办法用 JQuery 或 php 来做到这一点?(如果可能,请避免使用这些,最好使用 javascript).谢谢!

Yes, the function actually works (it knows when you click it and all), but it returns undefined for both x and y, so I'm assuming that the get x and y code in the function is incorrect. Any Ideas? I also know there isn't any built in functions within javascript itself to return the x and y like in java, ex.. would there be a way to do it with say JQuery or php? (avoid those if possible though, javascript would be best). Thanks!

推荐答案

像这样.

function printMousePos(event) {
  document.body.textContent =
    "clientX: " + event.clientX +
    " - clientY: " + event.clientY;
}

document.addEventListener("click", printMousePos);

MouseEvent - MDN

MouseEvent.clientX 只读
鼠标指针在本地(DOM 内容)坐标中的 X 坐标.

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY 只读
鼠标指针在本地(DOM 内容)坐标中的 Y 坐标.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

这篇关于javascript 在鼠标单击时获取 x 和 y 坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆