javascript - js拖拽问题,在浏览器外松开鼠标是停止不了拖拽的,如何解决
大家讲道理
大家讲道理 2017-04-10 15:53:42
[JavaScript讨论组]

以下代码在浏览器区域里面运行都是没问题的。但是当你缩小浏览器窗口,拖拽,然后再浏览器外面松开鼠标,再进入浏览器区域,竟然还是“不用按下鼠标就能拖拽”的现象,这算是bug吗?有方法解决吗?

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #dog {
            width: 150px;
            height: 150px;
            background: red;
            position: absolute;
        }
    </style>
    <script>
        window.onload = function () {
            var op = document.getElementById("dog");
            op.onmousedown = function (ev) {
                    var oEvent = ev || event;

                    var gapX = oEvent.clientX - op.offsetLeft;
                    var gapY = oEvent.clientY - op.offsetTop;

                    document.onmousemove = function (ev) {
                        var oEvent = ev || event;
                        //限制在可视区域内运动
                        var l = oEvent.clientX - gapX;
                        var t = oEvent.clientY - gapY;
                        var r = document.documentElement.clientWidth - op.offsetWidth;
                        var b = document.documentElement.clientHeight - op.offsetHeight;
                        if (l < 0) {
                            op.style.left = 0 + "px";
                        } else if (l > r) {
                            op.style.left = r + "px";
                        } else {
                            op.style.left = l + "px";
                        }
                        if (t < 0) {
                            op.style.top = 0 + "px";
                        } else if (t > b) {
                            op.style.top = b + "px";
                        } else {
                            op.style.top = t + "px";
                        }
                    }

                }
                //松开鼠标,停止拖拽
            op.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
    </script>
</head>

<body>
    <p id="dog"></p>
</body>

</html>

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
高洛峰

鼠标移到外部的时候为负值,所以做一下判定就好了。

巴扎黑

松开鼠标使用
document.onmouseup

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号