javascript——拖拽原理小实例
CSS代码:
#div1{ width: 100px; height: 100px; background: green; position: absolute;}
HTML代码:
<div id="div1"></div>
JS代码:
/* onmousedown : 选择元素 onmousemove : 移动元素 onmouseup : 释放元素 */ window.onload = function(){ var oDiv = document.getElementById('div1'); //鼠标按下时 oDiv.onmousedown = function(ev){ var ev = ev || event; // 获取鼠标点击时的距离位置 var disX = ev.clientX - this.offsetLeft; var disY = ev.clientY - this.offsetTop ; //鼠标移动时 document.onmousemove = function(ev){ var ev = ev || event; oDiv.style.left = ev.clientX - disX + 'px'; oDiv.style.top = ev.clientY - disY + 'px'; }; //鼠标释放时 document.onmouseup = function(){ document.onmousemove = document.onmouseup = null; } }; };
JS-demo2:
window.onload = function(){ /* 1.拖拽的时候,如果有文字被选中,会产生问题 原因:当鼠标按下的时候,如果页面中有文字被选中,那么会触发浏览器默认拖拽文字的效果 解决: 标准:阻止默认行为 非标准ie:全局捕获 */ var oDiv = document.getElementById('div1'); oDiv.onmousedown = function(ev){ var ev = ev || event; var disX = ev.clientX - this.offsetLeft; var disY = ev.clientY - this.offsetTop; if(oDiv.setCapture){ oDiv.setCapture(); } document.onmousemove = function(ev){ var ev = ev || event; oDiv.style.left = ev.clientX - disX + 'px'; oDiv.style.top = ev.clientY - disY + 'px'; }; document.onmouseup = function(){ document.onmousemove = document.onmouseup = null; if(oDiv.releaseCapture){ oDiv.releaseCapture(); } return false; }; }; };