js把盒子拖拽 封装为class类

 <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #box {
            width: 100px;
            height: 100px;
            background-color: brown;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
    
        /* 创建类 */
        class Drag {
            /* 构造器 */
            constructor(el) {
                    this.el = el
                    this.init();
                }
                /* 鼠标按下的方法 */
            Down(e) {
                    /* 获取鼠标按下的位置 */
                    var x = e.offsetX;
                    var y = e.offsetY;
                    /* 绑定鼠标移动事件 */
                    document.onmousemove = this.Move.bind(this, x, y)
                }
                /* 鼠标移动的方法 */
            Move(x, y, e) {
                    //盒子横坐标等于 与页面的距离-鼠标在盒子上按下的位置。
                    this.el.style.left = e.pageX - x + 'px'
                        //盒子纵坐标等于 与页面的距离-鼠标在盒子上按下的位置。
                    this.el.style.top = e.pageY - y + 'px'
                }
                /* 鼠标抬起的方法 */
            Up() {
                    /* 解绑移动事件 */
                    document.onmousemove = null;
                }
                /* 绑定事件 */
            init() {
                /* 绑定按下事件 */
                this.el.onmousedown = this.Down.bind(this)
                    /* 绑定抬起事件 */
                document.onmouseup = this.Up;
            }
        }
        /* 获取box */
        var box = document.getElementById('box')
            /* 调用 */
        var a = new Drag(box);
    </script>
</body>

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值