Javascript 检测鼠标点击位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6154911/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:27:48  来源:igfitidea点击:

Detect Mouse click location

javascripthtmleventsmouseevent

提问by Moon

What i am trying to achieve is make a DIV and display world map image on it or as a background.. & when user clicks some somewhere on the map, i catch the mouse-click location,

我想要实现的是制作一个 DIV 并在其上或作为背景显示世界地图图像..& 当用户单击地图上的某个位置时,我会捕捉到鼠标单击位置,

then i am some how going to translate the mouse's X,Y cords into longitude,latitude and then run an AJAX to display some data.

然后我将了解如何将鼠标的 X、Y 线转换为经度、纬度,然后运行 ​​AJAX 以显示一些数据。

My problem is:

我的问题是:

  • How to get mouse click location with JavaScript
  • How to translate the global click location into a DIV's relative X,Y coords of a layer
  • 如何使用 JavaScript 获取鼠标点击位置
  • 如何将全局点击位置转换为图层的 DIV 相对 X、Y 坐标

回答by evilone

In HTML you set onMouseMove event:

在 HTML 中设置 onMouseMove 事件:

<div onMouseMove="getPositions();"
style="width:200px;height:100px"></div>

And javascript function:

和 javascript 函数:

function getPositions(ev) {
if (ev == null) { ev = window.event }
   _mouseX = ev.clientX;
   _mouseY = ev.clientY;
}

回答by mgalgs

Unless you have a reason to do it from scratch, I would recommend Google Maps Api.

除非您有理由从头开始,否则我会推荐Google Maps Api

You'll notice that the Mapobject has a click event to which you can bind a callback that receives a MouseEvent that contains lat/long coords. Check out this example.

您会注意到Map对象有一个单击事件,您可以将一个回调绑定到该事件,该回调接收包含经纬度坐标的 MouseEvent。看看这个例子

回答by cchamberlain

In the event handler you can get it through the mouseEvent Args.

在事件处理程序中,您可以通过 mouseEvent Args 获取它。

Excerpt from http://msdn.microsoft.com/en-us/library/bb404721.aspx-

摘自http://msdn.microsoft.com/en-us/library/bb404721.aspx-

function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    // Return a Point object representing the x- and y-coordinates of the current mouse position
    // relative to the reference object.
    var pt = mouseEventArgs.getPosition(sender.findName("referenceObject"));

    // Display the current mouse position.
    sender.findName("Status").text = pt.x + " : " + pt.y;
}