原生Js实现拖拽(适用于pc和移动端)
效果:
HTML和CSS部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖拽demo</title> <style> #mydiv{ position: absolute; top: 0; left: 0; width: 100px; height: 100px; cursor: pointer; background-color: #de98f0; } </style> </head> <body> <div id="mydiv"></div> </body> </html>
Js部分
<script> var block = document.getElementById("mydiv"); var oW, oH; block.addEventListener("touchstart", function(e) { var touches = e.touches[0]; oW = touches.clientX - block.offsetLeft; oH = touches.clientY - block.offsetTop; document.addEventListener("touchmove", defaultEvent, false); }, false) block.addEventListener("touchmove", function(e) { var touches = e.touches[0]; var oLeft = touches.clientX - oW; var oTop = touches.clientY - oH; if (oLeft < 0) { oLeft = 0; } else if (oLeft > document.documentElement.clientWidth - block.offsetWidth) { oLeft = (document.documentElement.clientWidth - block.offsetWidth); } if (oTop < 0) { oTop = 0; } else if (oTop > document.documentElement.clientHeight - block.offsetHeight) { oTop = (document.documentElement.clientHeight - block.offsetHeight); } block.style.left = oLeft + "px"; block.style.top = oTop + "px"; }, false); block.addEventListener("touchend", function() { document.removeEventListener("touchmove", defaultEvent, false); }, false); function defaultEvent(e) { e.preventDefault(); } </script>
版权声明:本文为superlizhao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。