JavaScript获得鼠标点击x和y坐标 [英] javascript get x and y coordinates on mouse click

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

问题描述

我有一个小标签,当我点击它时( onClick 事件),它会运行 printMousePos()这是 HTML 标记:

 < html> ; 
< header>
<! - 顺便说一下,这不是实际的html文件,只是一个通用的例子。 - >
< script src ='game.js'>< / script>
< / header>
< body>
< div id =example>
< p id =test> x:,y:< / p>
< / div>
< / body>
< / html>

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

 函数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,ex ..会有办法做到这一点说JQuery或PHP? (尽可能避免这些,但javascript会是最好的)。感谢!

解决方案

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

MouseEvent - MDN


MouseEvent.clientX 只读

鼠标指针在本地(DOM内容)坐标中的X坐标。 p>

MouseEvent.clientY 只读

鼠标指针在本地(DOM内容)坐标中的Y坐标。



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>

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;
}

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!

解决方案

Like this.

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

document.addEventListener("click", printMousePos);

MouseEvent - MDN

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

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

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

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