使用“onclick”和 JavaScript 获取按钮上的 X/Y 坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5797468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get X/Y Coordinates on Button using 'onclick' and JavaScript
提问by nicorellius
I am a JavaScript beginner and am looking for a way to get the x and y coordinates on a button when it's clicked. This works in Opera, IE9 and Chrome but I can't get it to work in Firefox. Here is my code so far:
我是一名 JavaScript 初学者,正在寻找一种方法来在单击按钮时获取按钮上的 x 和 y 坐标。这适用于 Opera、IE9 和 Chrome,但我无法在 Firefox 中使用它。到目前为止,这是我的代码:
Function in JavaScript:
JavaScript 中的函数:
function buttonClick(subEvent)
{
var mainEvent = subEvent ? subEvent : window.event;
alert("This button click occurred at: X(" +
mainEvent.screenX + ") and Y(" + mainEvent.screenY + ")");
}
Here is the HTML section:
这是 HTML 部分:
<input type="button" onclick="buttonClick()" value="Submit"/>
The idea here is to only get the coordinates when the button is clicked and to get the actual coordinates within the border of the button itself. Getting coordinates on the screen is easier and finding that solution for all browsers was already accomplished.
这里的想法是仅在单击按钮时获取坐标,并获取按钮本身边界内的实际坐标。在屏幕上获取坐标更容易,并且已经为所有浏览器找到了解决方案。
Thanks in advance for any assistance.
在此先感谢您的帮助。
回答by Christian
You need to pass on the event. This is done as so:
你需要传递事件。这是这样做的:
<input type="button" onclick="buttonClick(event)" value="Submit"/>
^
'---- that one there