JavaScript:获取图像中单击的X,Y坐标

5

这是我的最新问题。

我正在尝试获取用户在图像中点击的X和Y坐标。无论它在用户的窗口中的位置,缩放比例,滚动位置,窗口大小,用户早餐吃了什么等等,X,Y坐标必须只考虑用户在图像中点击的位置,而不包括图像在屏幕上的位置,即图像中的左上点为0,0。(希望我解释得清楚。)

我之所以这样说,是因为在我的当前JavaScript函数中,我正在获取某个东西的X,Y坐标,但我不确定确切是什么。我认为它是用户在整个窗口中点击的位置,但不是在图像中的位置。这意味着如果图像的位置不同,如果用户已经滚动,如果我将图像移动到页面的其他位置等,则X,Y坐标会发生变化。以下是我的当前HTML代码:

<img id="hotspot_image" name="hotspot_image" style="width: 50%" src="misc/pages/hotspotimage.jpg" alt="Hotspot image" onclick="clickHotspotImage(event);"/>

以下是我的Javascript函数:

function clickHotspotImage(event) {
    var xOffset = document.getElementById('hotspot_image').offsetLeft;
    var xCoordinate = event.clientX;
    var yOffset = document.getElementById('hotspot_image').offsetTop;
    var yCoordinate = event.clientY;
    var hotspotlist = document.getElementById('hotspot_list').value;
    document.getElementById('hotspot_list').value = document.getElementById('hotspot_list').value + '\n' + xCoordinate + ',' + yCoordinate;
}

在代码的最后几行,将X、Y坐标对添加到名为hotspot_list的<textarea>标签中包含的列表的末尾。有谁知道我是否正确或者能指点我方向,或者知道我需要哪个缺失的部分才能得到真正的X、Y坐标?谢谢!

1个回答

6
你应该使用事件对象中的 offsetX 和 offsetY 来获取与触发事件的元素相关的鼠标坐标。如你所注意到的那样,clientX 和 clientY 将返回相对于窗口的鼠标坐标。

事件对象属性

这应该能解决问题。

function clickHotspotImage(event) {
    var xCoordinate = event.offsetX;
    var yCoordinate = event.offsetY;
    var hotspotlist = document.getElementById('hotspot_list').value;
    document.getElementById('hotspot_list').value = document.getElementById('hotspot_list').value + '\n' + xCoordinate + ',' + yCoordinate;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接