onmousemove问题?

justPassBy
  • 572

为什么设置document的onmousemove事件,拖拽时不会有问题,
而设置box的onmousemove事件拖拽时就会有问题呢?

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <title>完美拖拽</title>
    <style type="text/css">
        html,body{overflow:hidden;}
        body,div,h2,p{margin:0;padding:0;}
        body{color:#fff;background:#000;font:12px/2 Arial;}
        p{padding:0 10px;margin-top:10px;}
        span{color:#ff0;padding-left:5px;}
        #box{position:absolute;width:300px;height:150px;background:#333;border:2px solid #ccc;margin:-75px 0 0 -150px;}
        #box h2{height:25px;cursor:move;background:#222;border-bottom:2px solid #ccc;text-align:right;padding:0 10px;}
        #box h2 a{color:#fff;font:12px/25px Arial;text-decoration:none;outline:none;}
    </style>
    <script type="text/javascript">
        window.onload = function(){
            var box = document.getElementById("box");
            box.onmousedown = function(event){
                var x = event.offsetX;
                var y = event.offsetY;
                document.onmousemove = function(event){
                    var leftPos = event.clientX - x ;
                    var topPos = event.clientY - y;
                    box.style.left = leftPos + "px";
                    box.style.top = topPos + "px";
                };
            };
            box.onmouseup = function(){
                document.onmousemove = null;
            };
    };
    </script>
</head>
<body>
<div id="box" style=" left: 533px; top: 231px;">
    <h2><a href="javascript:;">点击回放拖动轨迹</a></h2>
    <p><strong>Drag:</strong><span>false</span></p>
    <p><strong>offsetTop:</strong><span>231</span></p>
    <p><strong>offsetLeft:</strong><span>533</span></p>
</div>


</body></html>
回复
阅读 3k
2 个回答

最好是委托在document上,委托在box上的话鼠标很容易脱离当前元素,导致移动失败

dilidili
  • 28

实验一次之后,问题出现在你的样式上。

#box{position:absolute;width:300px;height:150px;background:#333;border:2px solid #ccc;margin:-75px 0 0 -150px;}

删除这句话之后改为box虽然还是有些小BUG,但是基本上已经有了初步的效果。

代码改进:

  window.onload = function(){
            var box = document.getElementById("box");
            var onoff = false;
            var disx;
            var disy;
            box.onmousedown = function(ev){
                disx = ev.clientX - this.offsetLeft;
                disy = ev.clientY - this.offsetTop;
                onoff = true;
            };
            box.onmousemove = function(ev){
              if(onoff){
                var l = ev.clientX - disx ;
                var t = ev.clientY - disy;
                box.style.left = l + "px";
                box.style.top = t + "px";
              }
            };
            box.onmouseup = function(){
                onoff = false;
            };
    };

但是这样依然有些问题,如果鼠标在拖拽过程鼠标离开了box,那么就会出现BUG。
所以讲onmousemove和onmouseup设为document更好一些。

宣传栏