javascript使用拖动来移动元素

javascript使用拖动来移动元素

本文介绍了javascript使用拖动来移动元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置元素的位置?当用户拖动元素(图像)时,我想让它同步移动。我看到我的mousemove处理程序正在被调用。但是我无法让元素实际移动。

How does one set the position of an element? When the user drags an element (an image), I'd like to have it move synchronously. I see that my "mousemove" handler is being called. However I cannot get the element to actually move.

这是mousemove处理程序(被拖动的元素是overlay):

Here's the mousemove handler (the element being dragged is "overlay"):

function handleMouseMove (event)
{
  var deltaX = event.movementX;
  var deltaY = event.movementY;

  var divOverlay = document.getElementById ("overlay");
  var rect = divOverlay.getBoundingClientRect();

  divOverlay.style.left = rect.x + deltaX;
  divOverlay.style.top = rect.y + deltaY;
}

这是叠加的html:

<div id="overlay">
  ... some other stuff ...
  <img id="large" src="something.jpg" >
</div>

并且css:

#overlay {position:absolute; left:0; top:0}

看来默认拖动动作显示,这是叠加的阴影用鼠标移动。但元素本身不会移动。

It appears that the default drag action manifests, which is a shadow of "overlay" that moves with the mouse. But the element itself does not move.

推荐答案

不确定您的实际实现。但是这段代码可以工作:

Not sure about your actual implementation. However this code works:

要使用你的代码,这里是代码。您的代码的一个明显问题是您需要在style.left和style.right中添加px。您还不知道如何从代码中实际处理事件。使用此代码,元素移动一个圆圈,你需要修复它,但你明白了。

To do it using your code, here is the code. One obvious issue with your code is you need to add 'px' to your style.left and style.right. Also it is unknown how you actually handle the event from your code. Using this code, the element moves in a circle, you need to fix it but you get the idea.

var divOverlay = document.getElementById ("overlay");
var isDown = false;
divOverlay.addEventListener('mousedown', function(e) {
    isDown = true;
}, true);

document.addEventListener('mouseup', function() {
  isDown = false;
}, true);

document.addEventListener('mousemove', function(event) {
   event.preventDefault();
   if (isDown) {
   var deltaX = event.movementX;
   var deltaY = event.movementY;
  var rect = divOverlay.getBoundingClientRect();
  divOverlay.style.left = rect.x + deltaX + 'px';
  divOverlay.style.top  = rect.x + deltaX + 'px';
 }
}, true);






以下是另一种方法。

var offset = [0,0];
var divOverlay = document.getElementById ("overlay");
var isDown = false;

divOverlay.addEventListener('mousedown', function(e) {
isDown = true;
offset = [
    divOverlay.offsetLeft - e.clientX,
    divOverlay.offsetTop - e.clientY
 ];
}, true);

document.addEventListener('mouseup', function() {
   isDown = false;
}, true);

document.addEventListener('mousemove', function(e) {
    event.preventDefault();
    if (isDown) {
        divOverlay.style.left = (e.clientX + offset[0]) + 'px';
        divOverlay.style.top  = (e.clientY + offset[1]) + 'px';
   }
}, true);

这篇关于javascript使用拖动来移动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:56