jQuery拖拽效果,自己写的,能用

 jquery使用class,能用,jquery用原生

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 100px;
            height: 100px;
            margin-top: 100px;
            background-color: chartreuse;
            position: absolute;
        }
    </style>
    <script src="../js/jquer.min.js"></script>
    <!-- <script src="../js/util.js"></script> -->
</head>

<body>
    <div></div>
    <script>
        class Drag {
            constructor(ele) {
                this.ele = ele
                // 获取初始化盒子的位置
                this.boxT = ele.offset().top
                this.boxL = ele.offset().left
            }
            down() {
                // 点击
                this.ele.on('mousedown', (e) => {
                    // 获取初始化鼠标在盒子里面的位置
                    this.offsetX = e.offsetX
                    this.offsetY = e.offsetY
                    this.move()
                })
                // 停止
                $('html').on("mouseup", () => {
                    $('html').off("mousemove")
                })
            }
            move() {
                // 在HTML中移动
                $('html').on("mousemove", (e) => {
                    // 获取鼠标在文档的位置
                    let x = e.clientX
                    let y = e.clientY
                    // 设置元素的样式top left
                    this.ele.css("left", x - this.offsetX - this.boxL)
                    this.ele.css("top", y - this.offsetY - this.boxT + "px")
                })
            }
        }
        let div = $('div')
        new Drag(div).down()
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_54455551/article/details/124374817