How do you make a picture follow your mouse pointer with jquery?

后端 未结 2 1135
一向
一向 2020-12-03 11:50

I find drag-and-drop difficult (you know, keeping the mouse button depressed while moving), and want to offer a \'select and drop\' where a user clicks on an icon and clicks

相关标签:
2条回答
  • 2020-12-03 12:29

    The answer (using James Black's help) is:

    HTML

      <div id="sketch"></div>
      <img src="cat.jpg" class="follow" style="position: absolute;"/>
    

    JQuery

    $("#sketch").mousemove(function(e){
          $('.follow').css({'top': e.clientY - 20, 'left': e.clientX - 20});
    });
    

    Jsbin demo here.

    0 讨论(0)
  • 2020-12-03 12:35

    Just store the element in some variable that is accessible to the click event.

    So, have an onclick on every image: $('img').bind('click', function(e) { ... }); Then, when they click, just store the targetEvent somewhere and bind a click event to the drawing-plate.

    An interesting way would be to use a closure and bind that particular targetEvent so that in the event of a click on the drawing-plate you will know which one to move, but as long as you know, then you will just use an animation to move the img over to the new location.

    I forgot, you will also need to ensure that when an image is clicked on that the event handler that is already on the drawing-plate is removed before binding a new one.

    0 讨论(0)
提交回复
热议问题