#div1 { width: 100px; height: 100px; background: red; position: absolute; }
html
<div id="div1"> </div>
js
1 window.onload = function () { 2 var oDiv = document.getElementById(‘div1‘); 3 //pc端 4 oDiv.onmousedown = function (ev) { 5 var oEvent = ev || event; //需要获取和事件相关的信息时使用 6 var disX = oEvent.clientX - oDiv.offsetLeft; 7 var disY = oEvent.clientY - oDiv.offsetTop; 8 9 document.onmousemove = function (ev) { 10 var oEvent = ev || event; 11 var l = oEvent.clientX - disX; 12 var t = oEvent.clientY - disY; 13 14 if (l < 0) { 15 l = 0; 16 } else if (l > document.documentElement.clientWidth - oDiv.offsetWidth) { 17 l = document.documentElement.clientWidth - oDiv.offsetWidth; 18 } 19 20 if (t < 0) { 21 t = 0; 22 } else if (t > document.documentElement.clientHeight - oDiv.offsetHeight) { 23 t = document.documentElement.clientHeight - oDiv.offsetHeight; 24 } 25 26 oDiv.style.left = l + ‘px‘; 27 oDiv.style.top = t + ‘px‘; 28 }; 29 30 document.onmouseup = function () { 31 document.onmousemove = null; 32 document.onmouseup = null; 33 }; 34 }; 35 //移动端 36 // 拖拽 37 // 获取节点 38 var block = document.getElementById("right"); 39 var oW, oH; 40 // 绑定touchstart事件 41 oDiv.addEventListener("touchstart", function (e) { 42 var touches = e.touches[0]; 43 oW = touches.clientX - oDiv.offsetLeft; 44 oH = touches.clientY - oDiv.offsetTop; 45 //阻止页面的滑动默认事件 46 document.addEventListener("touchmove", defaultEvent, false); 47 }, false); 48 oDiv.addEventListener("touchmove", function (e) { 49 var touches = e.touches[0]; 50 var oLeft = touches.clientX - oW; 51 var oTop = touches.clientY - oH; 52 if (oLeft < 0) { 53 oLeft = 0; 54 } else if (oLeft > document.documentElement.clientWidth - oDiv.offsetWidth) { 55 oLeft = (document.documentElement.clientWidth - oDiv.offsetWidth); 56 } 57 oDiv.style.left = oLeft + "px"; 58 oDiv.style.top = oTop + "px"; 59 }, false); 60 oDiv.addEventListener("touchend", function () { 61 document.removeEventListener("touchmove", defaultEvent, false); 62 }, false); 63 64 function defaultEvent(e) { 65 e.preventDefault(); 66 }; 67 };