拖放div元素不能很好地工作

时间:2013-07-04 03:49:43

标签: javascript drag-and-drop

我创建了一个简单的代码来拖放div元素,但效果不佳 当您将div元素快速拖动到任何方向topleftrightdown时,鼠标光标将离开div元素,虽然我仍然按下按钮 。

HTML

<div id="box"></div>

CSS

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

的JavaScript

var elem = document.getElementById('box');
var PositionX = 0;
var PositionY = 0;
var MouseX = 0
var MouseY = 0;
var mouseDown = false;

elem.onmousedown = function(e) {
    PositionX = elem.offsetLeft;
    PositionY = elem.offsetTop;
    MouseX = e.clientX;
    MouseY = e.clientY;
    mouseDown = true;
};

elem.onmousemove = function(e) {
    if (mouseDown) {
    elem.style.left = PositionX + e.clientX - MouseX + "px";
    elem.style.top = PositionY + e.clientY - MouseY + "px";
  }
};

elem.onmouseover = function(e) {
    elem.style.cursor = 'move';
};

elem.onmouseup = function(e) {
    mouseDown = false;
};

You can see online

2 个答案:

答案 0 :(得分:0)

尝试更改这一行:

elem.onmousemove = function(e) {

为:

document.onmousemove = function(e) {

答案 1 :(得分:0)

试着希望它能完成你的工作:

var elem= document.getElementbyId('<%=box.ClientID%>');
elem.onmousemove= function(e) {
    if (mouseDown) {
    elem.style.left = PositionX + e.clientX - MouseX + "px";
    elem.style.top = PositionY + e.clientY - MouseY + "px";
  }
};