效果:

 

HTML和CSS部分

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>拖拽demo</title>
  6. <style>
  7. #mydiv{
  8. position: absolute;
  9. top: 0;
  10. left: 0;
  11. width: 100px;
  12. height: 100px;
  13. cursor: pointer;
  14. background-color: #de98f0;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="mydiv"></div>
  20. </body>
  21. </html>

  

Js部分

  1. <script>
  2. var block = document.getElementById("mydiv");
  3. var oW, oH;
  4. block.addEventListener("touchstart", function(e) {
  5. var touches = e.touches[0];
  6. oW = touches.clientX - block.offsetLeft;
  7. oH = touches.clientY - block.offsetTop;
  8. document.addEventListener("touchmove", defaultEvent, false);
  9. }, false)
  10.  
  11. block.addEventListener("touchmove", function(e) {
  12. var touches = e.touches[0];
  13. var oLeft = touches.clientX - oW;
  14. var oTop = touches.clientY - oH;
  15. if (oLeft < 0) {
  16. oLeft = 0;
  17. } else if (oLeft > document.documentElement.clientWidth - block.offsetWidth) {
  18. oLeft = (document.documentElement.clientWidth - block.offsetWidth);
  19. }
  20. if (oTop < 0) {
  21. oTop = 0;
  22. } else if (oTop > document.documentElement.clientHeight - block.offsetHeight) {
  23. oTop = (document.documentElement.clientHeight - block.offsetHeight);
  24. }
  25. block.style.left = oLeft + "px";
  26. block.style.top = oTop + "px";
  27. }, false);
  28.  
  29. block.addEventListener("touchend", function() {
  30. document.removeEventListener("touchmove", defaultEvent, false);
  31. }, false);
  32.  
  33. function defaultEvent(e) {
  34. e.preventDefault();
  35. }
  36. </script>

  

 

版权声明:本文为superlizhao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/superlizhao/archive/2004/01/13/8004012.html