使用jQuery在图像上单击鼠标的X/Y坐标 [英] getting the X/Y coordinates of a mouse click on an image with jQuery

查看:155
本文介绍了使用jQuery在图像上单击鼠标的X/Y坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery来获取图像上单击事件的X/Y坐标.坐标应该相对于图片,而不是相对于整个页面

I would like to use jQuery to get the X/Y coordinates of a click event on an image. The coordinates should be relative to the image, not relative to the whole page

推荐答案

您可以使用 pageXpageY 来获取鼠标在窗口中的位置.您还可以使用jQuery的 offset 来获取元素的位置.

You can use pageX and pageY to get the position of the mouse in the window. You can also use jQuery's offset to get the position of an element.

因此,对于距图像左侧的距离应该为pageX - offset.left,对于距图像顶部的距离应该为pageY - offset.top.

So, it should be pageX - offset.left for how far from the left of the image and pageY - offset.top for how far from the top of the image.

这里是一个例子:

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    alert(e.pageX - offset.left);
    alert(e.pageY - offset.top);
  });
});

我在这里做了一个实时示例

I've made a live example here and here is the source.

要计算距底部或右侧的距离,您必须使用jQuery的 width height 方法.

To calculate how far from the bottom or right, you would have to use jQuery's width and height methods.

这篇关于使用jQuery在图像上单击鼠标的X/Y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆