我创建了一个简单的代码来拖放两个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;
};
答案 0 :(得分:1)
使用position: absolute;
修复它。
如果您想要亲戚,请检查Implementing drag and drop on relatively positioned elements in JavaScript