js制作简单的盒子拖拽效果

代码如下:

    <style>
        #demo {
            width: 300px;
            height: 300px;
            background: #ccc;
            position: absolute;
        }
    </style>

<body>
    <input type="text">
    <div id="demo">asdfasf</div>
    <script>
        let demo = document.querySelector('#demo')
        let canMove = false
        let x = 0, y = 0
        demo.onmousedown = function (e) {
            x = e.pageX - demo.offsetLeft
            y = e.pageY - demo.offsetTop
            canMove = true
        }

        demo.oncontextmenu = function (e) {
            e.preventDefault()//在盒子上右击不会弹出默认菜单
        }

        setTimeout(() => {
        }, 2000);
        
        //鼠标点击与松开事件
        window.onmouseup = function () {
            canMove = false
        }

        window.onblur = function () {
            canMove = false
        }

        window.onmousemove = function (e) { //盒子移动的核心事件
            e.preventDefault(); //阻止默认行为
            if (canMove) {

                let left = e.pageX - x
                let top = e.pageY - y

                if (left < 0) left = 0//使盒子不能拖拽到顶部或左部以外
                if (top < 0) top = 0
                let maxLeft = window.innerWidth - demo.offsetWidth
                let maxTop = window.innerHeight - demo.offsetHeight
                if (left > maxLeft) left = maxLeft//通过计算,使盒子不能拖拽到页面屏幕以外
                if (top > maxTop) top = maxTop

                demo.style.left = left + "px"
                demo.style.top = top + 'px'
            }
        }
    </script>
</body>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值