鼠标拖拽效果

拖拽效果

通过javascript实现网页中鼠标按住拖动的效果。

网页效果

微信截图_20250401160209.png

代码展示

<html lang="zh">

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

        html,
        body {
            width: 100%;
            height: 100%;
        }

        html {
            font-size: 10px;
        }

        .box {
            width: 50rem;
            height: 30rem;
            background-color: red;
            position: relative;
        }
    </style>
</head>

<body>
    <div class="box" id="box"></div>
    <script>
        let box = document.getElementById("box");
        box.onmousedown = function (e) {
            let offsetX = e.offsetX;
            let offsetY = e.offsetY;
            console.log(offsetX, "offsetX");
            console.log(offsetY, "offsetY");
            document.onmousemove = function (e2) {
                let clientX = e2.clientX;
                let clientY = e2.clientY;
                console.log(clientX, "clientX");
                console.log(clientY, "clientY");
                _left = clientX - offsetX;
                _top = clientY - offsetY;
                console.log(_left, "left");
                console.log(_top, "top");
                if (_left < 0) {
                    _left = 0;
                }
                if (_top < 0) {
                    _top = 0;
                }
                if (_left > document.documentElement.clientWidth - box.offsetWidth) {
                    _left = document.documentElement.clientWidth - box.offsetWidth;
                }
                if (_top > document.documentElement.clientHeight - box.offsetHeight) {
                    _top = document.documentElement.clientHeight - box.offsetHeight;
                }
                box.style.left = _left + "px";
                box.style.top = _top + "px";
            }
        }
        document.onmouseup = function () {
            document.onmousemove = null;
        }
    </script>
</body>

</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 效果主要是实现网页中内容模块的鼠标拖拽,主要代码如下: <!DOCTYPE html> 鼠标拖动事件操作 #bo...
    L_2936阅读 503评论 0 0
  • 常用的鼠标事件有onmousedown(鼠标按下)、onmousemove(鼠标拖动)、onmouseup(鼠标弹...
    姜治宇阅读 4,976评论 0 0
  • 成果展示 按住图中蓝色方块儿可拖到任意位置,松手后蓝色方块儿位置不动初始位置 鼠标拖拽后,拖到想要的位置放手即可比...
    _Liu_阅读 34评论 0 0
  • 鼠标拖拽效果分为3个事件 鼠标按下事件onmousedown, 事件源是点击的对象, 就是我们要拖拽的对象 鼠标移...
    LiYajie阅读 5,113评论 0 1
  • 本次编写结果 代码展示:<!DOCTYPE html> Document #box {position: abs...
    风流_8cce阅读 793评论 0 0