簡體   English   中英

使用具有正確光標定位的Javascript移動元素

[英]Moving element with Javascript with correct cursor positioning

如何在用光標正確定位元素的同時用鼠標移動元素?

像這個小提琴一樣,div總是跳到其0x0位置:

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/

將元素width的一半減到left ,將元素height的一半height 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM