javascript get x and y coordinates on mouse click(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="Z2FtZS5qcw=="></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 坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:javascript 在鼠标单击时获取 x 和 y 坐标


- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01