拖拽

一、拖拽实例,定义一个div使鼠标按下时任意拖拽,鼠标松开后,div固定

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #div1 {
            width: 100px;
            height: 100px;
            background: #ccc;
            position: absolute;
        }
    </style>
    <script>
       window.onload = function () {
           var oDiv = document.getElementById('div1');
           var disX = 0;
           var disY = 0;
           //如果在div上加事件,鼠标运行快了移除div,div不会移动。所以直接给document加事件
           document.onmousedown = function (ev) {
               var oEvent = ev || event;
               disX = oEvent.clientX - oDiv.offsetLeft;
               disY = oEvent.clientY - oDiv.offsetTop;

               document.onmousemove = function (ev) {
                   var oEvent = ev || event;
                   var l = oEvent.clientX -disX;
                   var t = oEvent.clientY-disY;
                   //防止拖出页面,加了上下左右判断
                   if(l<0){
                       l = 0;
                   }else if(l>document.documentElement.clientWidth-oDiv.offsetWidth){
                       l = document.documentElement.clientWidth-oDiv.offsetWidth;
                   }
                   if(t<0){
                       t=0;
                   }else if(t>document.documentElement.clientHeight-oDiv.offsetHeight){
                       t = document.documentElement.clientHeight-oDiv.offsetHeight
                   }
                   oDiv.style.left =l +'px';
                   oDiv.style.top = t+'px';
               };
               document.onmouseup = function () {
                   document.onmousemove = null;
                   document.onmouseup = null;
               };
               //为了修复:火狐浏览器下空div拖拽有bug,使用阻止默认事件
               return false;
           };
       };
    </script>
</head>

<body>
  <div id="div1">

</div>
</body>
</html>

 

posted on 2017-05-15 14:02  懂你在爱我  阅读(195)  评论(0)    收藏  举报

导航