简体   繁体   中英

Moving element with Javascript with correct cursor positioning

How can I move elements with the mouse whilst positioning them correct with the cursor?

Like in this fiddle the div always jumps to its 0x0 position:

var isMouseDown = false;

$('div')
    .mousedown(function() {
    isMouseDown = true;
  })
  .mouseup(function() {
    isMouseDown = false;
  })
  .mousemove(function(event) {
    if(isMouseDown) {
        $(this).css({
        'top': event.pageY, // Offset missing
        'left': event.pageX
      });
    }
  });

https://jsfiddle.net/Lc844Lea/5/

Subtract half of the width of the element to left and half of the height of the element to top .

var isMouseDown = false;
$('div').mousedown(function() {
    isMouseDown = true;
}).mouseup(function() {
    isMouseDown = false;
}).mousemove(function(event) {
    var heightWidth = this.getBoundingClientRect().height/2;
    if(isMouseDown) {
      $(this).css({'top': event.pageY - heightWidth,'left': event.pageX - heightWidth });
    }
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM