JS在页面渲染一个div,用鼠标点击鼠标随意拖动该元素,当鼠标松开时,该元素会停在鼠标松开的页面位置。

<style>
    #goods {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        position: fixed;
        background-color: greenyellow;
    }
 
</style>

<body>
    <script>
        // 让元素跟随鼠标移动
        let goods = document.createElement('div');
        document.body.appendChild(goods);
        goods.setAttribute('id', 'goods')
        goods.onmousedown = function (e) { // 给元素绑定鼠标按下事件
            // 当鼠标按下时,获取鼠标相对于元素的坐标
            let mousedownX = e.offsetX;
            let mousedownY = e.offsetY;
            document.onmousemove = function (event) {
                // 当鼠标移动时,获取鼠标移动的坐标
                let mousemoveX = event.clientX
                let mousemoveY = event.clientY

                // 把鼠标移动的位置重新赋值给 元素的位置  并且减去鼠标在元素上按下时的初始坐标可以让元素一直处于移动状态
                goods.style.left = (mousemoveX - mousedownX) + 'px'
                goods.style.top = (mousemoveY - mousedownY) + 'px'
            }
        }
        // 在新位置 结束移动事件,让元素停在新位置
        document.onmouseup = function () {
            // 删除鼠标的移动事件
            document.onmousemove = null;
        }
    </script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值