参看代码:https://jsbin.com/munuzureya/edit?html,js,output

一、步骤

有 3 个状态

  1. 点击时:进入可拖动状态
  2. 拖动时:计算拖动前后的偏移量的值并不断刷新最新位置
  3. 弹起时:进入不可拖动状态

代码如下

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9. <div id="xxx"></div>
  10. </body>
  11. </html>
  1. div{
  2. border: 1px solid red;
  3. position: absolute;
  4. top: 0;
  5. left: 0;
  6. width: 100px;
  7. height: 100px;
  8. }
  9. *{margin:0; padding: 0;}
  1. var dragging = false
  2. var position = null
  3. xxx.addEventListener('mousedown',function(e){
  4. dragging = true
  5. position = [e.clientX, e.clientY]
  6. })
  7. document.addEventListener('mousemove', function(e){
  8. if(dragging === false){return}
  9. console.log('hi')
  10. const x = e.clientX
  11. const y = e.clientY
  12. const deltaX = x - position[0]
  13. const deltaY = y - position[1]
  14. const left = parseInt(xxx.style.left || 0)
  15. const top = parseInt(xxx.style.top || 0)
  16. xxx.style.left = left + deltaX + 'px'
  17. xxx.style.top = top + deltaY + 'px'
  18. position = [x, y]
  19. })
  20. document.addEventListener('mouseup', function(e){
  21. dragging = false
  22. })

「@浪里淘沙的小法师」