HTML代码:
<p> ksjdfkjlksjfdksjfskjfskljldffffffffffffffffffffffff </p> <div id="div"></div>
css代码:
<style> body{ padding: 0; margin: 0; } #div{ width: 100px; height: 100px; background: #cc0000; position: absolute; left: 0; top: 0; } .newbox{ width: 100px; height: 100px; background: rgba(255,0,0,.3); position: absolute; left: 0; top: 0; } </style>
js代码:
<script> window.onload = function () { var oBox = document.getElementById('div'); oBox.onmousedown = function (ev) { //克隆原div ,拖拽时的阴影 var newBox = oBox.cloneNode(); newBox.removeAttribute('id'); newBox.className = 'newbox'; document.body.appendChild(newBox); //鼠标点击位置到移动元素所在的外框的距离 var oEvent = ev||event; var disX = oEvent.clientX - newBox.offsetLeft; var disY = oEvent.clientY - newBox.offsetTop; document.onmousemove = function (ev) { var oEvent = ev||event; var left = oEvent.clientX - disX; var top = oEvent.clientY - disY; if (left<0){ left = 0; } else if (left>document.documentElement.clientWidth - oBox.offsetWidth){ left = document.documentElement.clientWidth - oBox.offsetWidth; } if (top < 0){ top = 0; } else if(top > document.documentElement.clientHeight - oBox.offsetHeight) { top = document.documentElement.clientHeight - oBox.offsetHeight; } newBox.style.top = top +'px'; newBox.style.left = left + 'px'; } document.onmouseup = function () { oBox.style.top = newBox.style.top; oBox.style.left = newBox.style.left; document.body.removeChild(newBox); document.onmousemove = null; document.onmouseup = null; oBox.releaseCapture && oBox.releaseCapture();//IEA独有的释放捕获 } /*为消除拖拽时会选中旁边的文字*/ return false; //清除系统默认事件 oBox.setCapture && oBox.setCapture();//IE独有的捕获鼠标 /* 在指定窗口里设置鼠标捕获。一旦窗口捕获了鼠标,所有鼠标输入都针对该窗口,无论光标是否在窗口的边界内。同一时刻只能有一个窗口捕获鼠标。如果鼠标光标在另一个线程创建的窗口上,只有当鼠标键按下时系统才将鼠标输入指向指定的窗口。 * */ } } </script>