拖放div元素在元素一上运行良好,但元素2不太好

时间:2013-07-08 05:44:45

标签: javascript drag-and-drop

我创建了一个简单的代码来拖放两个div元素但在div 1上运行良好,但div 2效果不佳。
鼠标光标未正确显示在div 2上。

请查看问题底部的在线演示链接。

HTML

<div class="draggable"></div>
<div class="draggable"></div>

CSS

div.draggable {
  background-color:yellowgreen; 
  width:150px; 
  height:100px; 
  border:1px solid #ffff66; 
  position:relative; 
}

的JavaScript

var element = null;
var elemPosL = 0;
var elemPosT = 0;
var isMouseDown = false;

document.onmousedown = function(e) {
    element = e.target;
    if (element.className === "draggable") {
        elemPosL = e.clientX - element.offsetLeft;
        elemPosT = e.clientY - element.offsetTop;
        isMouseDown = true;
    }
};

document.onmousemove = function(e) {
    if (isMouseDown) {
        element.style.left = e.clientX - elemPosL + "px";
        element.style.top = e.clientY - elemPosT + "px";
    }
};


document.onmouseup = function() {
    isMouseDown = false;
    element = null;
};

You can see online

1 个答案:

答案 0 :(得分:1)

使用position: absolute;修复它。

如果您想要亲戚,请检查Implementing drag and drop on relatively positioned elements in JavaScript