问题描述
我有一个小标签,当我点击它时( onClick
事件),它会运行 printMousePos()$ c $功能。
这是 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);
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);
这篇关于JavaScript获得鼠标点击x和y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!