原生js实现div拖拽 (考虑浏览器兼容性)

参考代码:

var drag1 = document.getElementById(‘drag1’);

drag1.onmousedown = function(ev){

   var x = ev.clientX - drag1.offsetLeft;

   var y = ev.clientY - drag1.offsetTop;

   drag1.onmousemove =  function(ev){

      drag1.style.left = ev.clientX-x+'px';

      drag1.style.top = ev.clientY-y + 'px';

   }

  drag1.onmouseup = function ( ev ) {

  drag1.οnmοusemοve=drag1.οnmοuseup=null;

  }

}

前提是:要给div设置有定位属性position

 

转载于:https://www.cnblogs.com/lbcxq/p/8658135.html

你可能感兴趣的:(原生js实现div拖拽 (考虑浏览器兼容性))