首页 > js拖拽问题,在浏览器外松开鼠标是停止不了拖拽的,如何解决

js拖拽问题,在浏览器外松开鼠标是停止不了拖拽的,如何解决

以下代码在浏览器区域里面运行都是没问题的。但是当你缩小浏览器窗口,拖拽,然后再浏览器外面松开鼠标,再进入浏览器区域,竟然还是“不用按下鼠标就能拖拽”的现象,这算是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 odiv = document.getElementById("dog");
            odiv.onmousedown = function (ev) {
                    var oEvent = ev || event;

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

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

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

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

</html>


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


松开鼠标使用
document.onmouseup

【热门文章】
【热门文章】