0

I am trying to insert an image in a div based on where the user clicks. This seems to work fine, unless the div is scrollable, and then the position of the image remains the same regardless of where we've scrolled to. The image should remain in the same place relative to the content within the div.

JSFiddle

Code:

$("#a").on("click",function(e){

    var top=e.pageY-$(this).position().top,
        left=e.pageX-$(this).position().left;

    $('.imgajoutee').remove();
    $(this).append("<img src='https://upload.wikimedia.org/wikipedia/commons/0/0c/Dive_hand_signal_OK_1.png' class='imgajoutee' style='top:"+top+"px;left:"+left+"px;'/>");

});
4

1 回答 1

1

您需要做几件事:

  • 更改您的imgCSS,使其positionabsolute而不是fixed
  • 您还需要更改您的容器(在这种情况下#a)以拥有一个position:relative
  • 最后,您的计算top应该更改为使用.offset()而不是position()并添加.scrollTop()容器的值。这会计算容器滚动了多少。

考虑到所有这些因素,请参阅更新的 JSFiddle

CSS

#a { position:relative; }
img { position: absolute; }

JS

$("#a").on("click",function(e) {
    var top = $(this).scrollTop() + e.pageY - $(this).offset().top,
        left = e.pageX-$(this).offset().left;
    ...
});
于 2013-08-20T10:36:57.520 回答