原生JS实现拖拽效果-兼容IE
原生JavaScript实现拖拽效果,要用到三个事件:onmousedown、onmousemove、onmouseup;而且使用有一定的顺序,不能用错;详细的在代码中解释。
基本样式:要让元素绝对定位,脱离文档流,方便拖拽。
#box{ position:absolute; cursor:pointer; width:100px; height:100px; background:#f00; }
js代码:
1 window.onload = function(){ 2 var box = document.getElementById('box'); 3 box.onmousedown=function(e){ 4 5 e = e || window.event; 6 //点击时,鼠标距离元素左 上的距离 7 var boxLeft = e.clientX - box.offsetLeft;//e.clientX:鼠标距离文档左边的距离 box.offsetLeft:元素距离左边的距离 8 var boxTop = e.clientY - box.offsetTop; 9 //setCapture()/releaseCapture()这两个方式是IE特有的,可以捕获鼠标滑动到窗口外的事件 10 if(typeof box.setCapture == 'object'){ 11 //IE 12 13 box.onmousemove=mouseMove; 14 box.onmouseup=mouseUp; 15 box.setCapture(); 16 }else{ 17 window.onmousemove = mouseMove; 18 window.onmouseup = mouseUp; 19 } 20 21 22 23 function mouseMove(e){ 24 e = e || window.event; 25 //计算元素记录文档的左,上的距离 26 var L = e.clientX - boxLeft; 27 var T = e.clientY - boxTop; 28 29 if(L <= 0){ 30 //超出左边界 31 L = 0; 32 }else if(L > document.documentElement.clientWidth - box.offsetWidth){ 33 //超出右边界 34 L = document.documentElement.clientWidth - box.offsetWidth; 35 } 36 37 if(T <= 0){ 38 //超出上边界 39 T = 0; 40 }else if(T > document.documentElement.clientHeight - box.offsetHeight){ 41 //超出下边界 42 T = document.documentElement.clientHeight - box.offsetHeight; 43 } 44 45 box.style.left = L +"px"; 46 box.style.top = T + "px"; 47 } 48 49 function mouseUp(){ 50 if(typeof box.releaseCapture == 'object'){ 51 //IE 52 box.releaseCapture(); 53 } 54 55 this.onmousemove = null; 56 this.onmouseup = null; 57 } 58 59 } 60 }