1. <!DOCTYPE html>
    2. <html lang="en">
    3. <body>
    4. <span id="bar" style="position: relative;border: 1px solid red;">长按拖拽</span>
    5. <script>
    6. const mydiv = document.getElementById("bar");
    7. // 需要补充一个开关
    8. mydiv.onmousedown = function (event) {
    9. document.onmousemove = function () {
    10. // x 和 y 的最大值和最小值略
    11. let x2 = window.event.clientX,y2 = window.event.clientY;
    12. mydiv.style.top = `${y2}px`
    13. mydiv.style.left = `${x2}px`
    14. }
    15. }
    16. // 拖拽完成 解绑mousemove事件
    17. window.onmouseup = function () {
    18. document.onmousemove = null
    19. }
    20. </script>
    21. </body>
    22. </html>