如何使用纯 javascript 在屏幕上平滑地拖动图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17992543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:22:38  来源:igfitidea点击:

How do I drag an image smoothly around the screen using pure javascript

javascript

提问by Laurence

I'm trying to use JavaScript drag an image around the screen. I've already written a script that works fine on divs with text, but when I use it on a image it works very intermittently.

我正在尝试使用 JavaScript 在屏幕上拖动图像。我已经编写了一个脚本,可以在带有文本的 div 上正常工作,但是当我在图像上使用它时,它会间歇性地工作。

I have put my code on jsfiddle so others can see what I mean. http://jsfiddle.net/laurence/YNMEX/

我已将我的代码放在 jsfiddle 上,以便其他人可以明白我的意思。 http://jsfiddle.net/laurence/YNMEX/

If you run it you will find that the text block can be dragged and dropped, but when you try the same thing with the image, it leaves the image behind. It's like the image can't keep up with the movement of the mouse.

如果您运行它,您会发现可以拖放文本块,但是当您对图像尝试相同的操作时,它会将图像抛在后面。就好像图像跟不上鼠标的移动。

I have repeated the code on jsfiddle below:

我在下面的 jsfiddle 上重复了代码:

function startDrag(e) {
  // determine event object
  if (!e) {
    var e = window.event;
  }

  // IE uses srcElement, others use target
  var targ = e.target ? e.target : e.srcElement;

  if (targ.className != 'dragme') {
    return
  };
  // calculate event X, Y coordinates
  offsetX = e.clientX;
  offsetY = e.clientY;

  // assign default values for top and left properties
  if (!targ.style.left) {
    targ.style.left = '0px'
  };
  if (!targ.style.top) {
    targ.style.top = '0px'
  };

  // calculate integer values for top and left 
  // properties
  coordX = parseInt(targ.style.left);
  coordY = parseInt(targ.style.top);
  drag = true;

  // move div element
  document.onmousemove = dragDiv;
}

function dragDiv(e) {
  if (!drag) {
    return
  };
  if (!e) {
    var e = window.event
  };
  var targ = e.target ? e.target : e.srcElement;
  // move div element
  targ.style.left = coordX + e.clientX - offsetX + 'px';
  targ.style.top = coordY + e.clientY - offsetY + 'px';
  return false;
}

function stopDrag() {
  drag = false;
}
window.onload = function() {
  document.onmousedown = startDrag;
  document.onmouseup = stopDrag;
}
.dragme {
  position: relative;
  width: 270px;
  height: 203px;
  cursor: move;
}

#draggable {
  background-color: #ccc;
  border: 1px solid #000;
}
<div id="draggable" class="dragme">"Hello World!"</div>
<img src="https://picsum.photos/270/203" alt="drag-and-drop image script" title="drag-and-drop image script" class="dragme">

采纳答案by n3rd

Simply add return falseat the end of your startDragfunction to keep the browser from handling the click event.

只需return falsestartDrag函数的末尾添加以防止浏览器处理点击事件。

回答by Gigy

Also targshould be assigned only on startDragand global(without var):

targ应该只在startDragglobal(没有var)上分配:

http://jsfiddle.net/gigyme/YNMEX/132/

http://jsfiddle.net/gigyme/YNMEX/132/

<script type="text/javascript">
    function startDrag(e) {
            // determine event object
            if (!e) {
                var e = window.event;
            }
            if(e.preventDefault) e.preventDefault();

            // IE uses srcElement, others use target
            targ = e.target ? e.target : e.srcElement;

            if (targ.className != 'dragme') {return};
            // calculate event X, Y coordinates
                offsetX = e.clientX;
                offsetY = e.clientY;

            // assign default values for top and left properties
            if(!targ.style.left) { targ.style.left='0px'};
            if (!targ.style.top) { targ.style.top='0px'};

            // calculate integer values for top and left 
            // properties
            coordX = parseInt(targ.style.left);
            coordY = parseInt(targ.style.top);
            drag = true;

            // move div element
                document.onmousemove=dragDiv;
            return false;

        }
        function dragDiv(e) {
            if (!drag) {return};
            if (!e) { var e= window.event};
            // var targ=e.target?e.target:e.srcElement;
            // move div element
            targ.style.left=coordX+e.clientX-offsetX+'px';
            targ.style.top=coordY+e.clientY-offsetY+'px';
            return false;
        }
        function stopDrag() {
            drag=false;
        }
        window.onload = function() {
            document.onmousedown = startDrag;
            document.onmouseup = stopDrag;
        }
</script>

回答by Dharmesh Patel

You may add e.preventDefault();at the end of your startDragfunction

您可以e.preventDefault();startDrag函数末尾添加

回答by sambuca

Bind a specific elementof the drag event.

绑定拖动事件的特定元素

function log() {
    var debug = true;
    if (!debug)
        return;
    if (arguments) {
        for (var i = 0; i < arguments.length; i++) {
            console.log(arguments[i]);
        }
    }
}    

function Drag(element) {
    this.dragging = false;
    this.mouseDownPositionX = 0;
    this.mouseDownPositionY = 0;
    this.elementOriginalLeft = 0;
    this.elementOriginalTop = 0;
    var ref = this;
    this.startDrag = function (e) {
        e.preventDefault();
        ref.dragging = true;
        ref.mouseDownPositionX = e.clientX;
        ref.mouseDownPositionY = e.clientY;
        ref.elementOriginalLeft = parseInt(element.style.left);
        ref.elementOriginalTop = parseInt(element.style.top);
        // set mousemove event
        window.addEventListener('mousemove', ref.dragElement);
        log('startDrag');
    };
    this.unsetMouseMove = function () {
        // unset mousemove event
        window.removeEventListener('mousemove', ref.dragElement);
    };
    this.stopDrag = function (e) {
        e.preventDefault();
        ref.dragging = false;
        ref.unsetMouseMove();
        log('stopDrag');
    };
    this.dragElement = function (e) {
        log('dragging');
        if (!ref.dragging)
            return;
        e.preventDefault();
        // move element
        element.style.left = ref.elementOriginalLeft + (e.clientX - ref.mouseDownPositionX) + 'px';
        element.style.top = ref.elementOriginalTop + (e.clientY - ref.mouseDownPositionY) + 'px';
        log('dragElement');
    };
    element.onmousedown = this.startDrag;
    element.onmouseup = this.stopDrag;
}

var myDrag = new Drag(yourElement);// bind event
console.log(myDrag.dragging);