盒子拖动案例

本文通过一个简单的盒子拖动案例,介绍了JavaScript中onmousedown事件的应用。文章详细讲解了实现拖动功能的步骤,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js



前言

 以下是鼠标事件,点击盒子拖动。

#一、使用步骤

1.代码如下

代码如下(示例):

<!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;
        }

        #box1 { 
            background-color: chartreuse;
            position: fixed;
            top: 0;
            left: 0;

        }

        #box2 {
           
            background-color: crimson;
            position: fixed;
            top: 0;
            right: 0;

        }
        .box {
            width: 300px;
            height: 300px;
        }
    </style>
</head>

<body>
    <div id="box1" class="box"></div>
    <div id="box2" class="box"></div>


    <script>
        document.querySelectorAll('.box').forEach(box => {
            box.onmousedown = function (e) {
                // console.log(e.clientX,e.clientY);//当时事件触发时,鼠标距离屏幕的xy轴距离
                // console.log(this.offsetLeft, this.offsetTop);//当前盒子距离屏幕xy轴的距离
                let disX = e.clientX - this.offsetLeft,
                     disY = e.clientY - this.offsetTop;

                document.onmousemove = function (e) {

                    let left = e.clientX - disX,
                        top = e.clientY - disY;

                    box.style.left = left + 'px';
                    box.style.top = top + 'px';
                }

                document.onmouseup = function(e){
                    document.onmousemove = null;
                    document.onmouseup = null;

                }
            }
        })
    </script>
</body>

</html>

总结

本文仅仅简单介绍了onmousedown事件的使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值