最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the part of an image where the user clicked - Stack Overflow

programmeradmin0浏览0评论

Is it possible to find where the user clicked on the image?

I have an image - and onto the image the user can click. And I am trying to find a way, how to get the place, when the user clicked.

Is it possible to find where the user clicked on the image?

I have an image - and onto the image the user can click. And I am trying to find a way, how to get the place, when the user clicked.

Share Improve this question edited Jul 25, 2019 at 16:04 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 28, 2011 at 4:48 user1946705user1946705 2,88814 gold badges43 silver badges58 bronze badges 1
  • 1 Are you looking for imagemap? – Mrchief Commented Jul 28, 2011 at 4:58
Add a ment  | 

3 Answers 3

Reset to default 6

On image click you can find the coordinates where the user clicked using the event object.

$("imageSelector").click(function(e){
  var pos = $(this).position();
  //The following are the x/y coordinates of the mouse click relative to image.
  var x = e.pageX - pos.left;
  var y = e.pageY - pos.top;
});

Don't be fooled by methods that fail to take margin, padding, and border into account!

This is the code you need. :

$("#myImage").click ( function (evt) {

    var jThis               = $(this);
    var offsetFromParent    = jThis.position ();
    var topThickness        = (jThis.outerHeight(true) - jThis.height() ) / 2;
    var leftThickness       = (jThis.outerWidth (true) - jThis.width () ) / 2;

    //--- (x,y) coordinates of the mouse click relative to the image.
    var x                   = evt.pageX - offsetFromParent.left - leftThickness;
    var y                   = evt.pageY - offsetFromParent.top  - topThickness;
} );


See it in action at jsFiddle.


You can get the mouse position easily, and then you can add something to that point relative to the image.

Here's an example of mouse position: jquery.

发布评论

评论列表(0)

  1. 暂无评论