js拖拽

function drag(cla1,cla2,index){//鼠标可拖拽区域的dom,被拖拽的dom元素,索引
     var disX = 0; //鼠标到dom元素左边距离
     var disY = 0; //鼠标到dom元素上边距离
     var oDiv1 = document.getElementsByClassName(cla1)[index];
     var oDiv2 = document.getElementsByClassName(cla2)[index];
     oDiv1.onmousedown = function(ev){
          var ev = ev || window.event;
          disX = ev.clientX - this.offsetLeft;
          disY = ev.clientY - this.offsetTop;
          document.onmousemove = function(ev){
               oDiv2.style.left = ev.clientX - disX + 'px';
               oDiv2.style.top = ev.clientY - disY + 'px';
               if(ev.clientX - disX>=document.body.clientWidth-oDiv2.offsetWidth){ //当拖动dom超过页面右边边界
                   oDiv2.style.left = document.body.clientWidth-oDiv2.offsetWidth + 'px';
               }
               if(ev.clientX - disX <= 0){ //当拖动dom超过左边边界
                   oDiv2.style.left = 0;
               }
               if(ev.clientY - disY>=document.body.clientHeight-oDiv2.offsetHeight){ //当拖动dom超过页面下边边界
                   oDiv2.style.top = document.body.clientHeight-oDiv2.offsetHeight + 'px';
               }
               if(ev.clientY - disY <= 0){//当拖动dom超过上边边界
                   oDiv2.style.top = 0;
               }
         }
         document.onmouseup = function(ev){ //鼠标抬起移除鼠标move事件
              document.onmousemove = null;
         }
    }
    return false;
} var divBox = document.getElementsByClassName('divBox'); for(let i = 0 ; i < divBox.length; i++ ){ drag('divHeader','divBox',i) }
posted @ 2018-07-26 14:57  疯狂的前端  阅读(765)  评论(0编辑  收藏  举报