原生js实现拖拽功能

x33g5p2x  于2022-03-09 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(386)

一、写在前面
如果我们想要实现拖拽的功能,必须要知道三个事件:
1、onmousedown:鼠标按下事件
2、onmousemove:鼠标移动事件
3、onmouseup:鼠标抬起事件
二、实现思路

  1. 我们当左键点击时,需要记录当前的鼠标点击位置相对于该元素左上角的xy坐标,
  2. 这里我们使用diffXdiffY来表示。然后我们移动时需要不断计算当前元素距离浏
  3. 览器左边和上边的距离。然后给元素进行赋值。当鼠标抬起时,然后取消鼠标移动事
  4. 件和鼠标抬起事件。

三、代码

  1. <div id="drag"></div>
  1. * {
  2. margin: 0px;
  3. padding: 0px;
  4. }
  5. #drag {
  6. width: 200px;
  7. height: 200px;
  8. background: red;
  9. cursor: pointer;
  10. position: absolute;
  11. }
  1. <script>
  2. window.onload = function() {
  3. //获取drag元素
  4. let drag = document.getElementById("drag")
  5. //当鼠标按下时
  6. drag.onmousedown = function(e) {
  7. //做到浏览器兼容
  8. e = e || window.event
  9. let diffX = e.clientX - drag.offsetLeft
  10. let diffY = e.clientY - drag.offsetTop
  11. //当拉着box移动时
  12. document.onmousemove = function(e) {
  13. // 浏览器兼容
  14. e = e || window.event
  15. let left = e.clientX - diffX
  16. let top = e.clientY - diffY
  17. if(left < 0) {
  18. left = 0
  19. }else if(left > window.innerWidth - drag.offsetWidth){
  20. left = window.innerWidth - drag.offsetWidth
  21. }
  22. if(top < 0) {
  23. top = 0
  24. }else if(top > window.innerHeight - drag.offsetHeight) {
  25. top = window.innerHeight - drag.offsetHeight
  26. }
  27. drag.style.left = left + 'px'
  28. drag.style.top = top + 'px'
  29. }
  30. // 当鼠标抬起时
  31. document.onmouseup = function(e) {
  32. this.onmousemove = null
  33. this.onmouseup = null
  34. }
  35. }
  36. }
  37. </script>

相关文章