0

我正在使用以下函数通过句柄拖动 div:

function enableDragging(ele) {
    var dragging = dragging || false,
        x, y, Ox, Oy,
        current;
    enableDragging.z = enableDragging.z || 1;
    var grabber = document.getElementById("wrapId");
    grabber.onmousedown = function (ev) {
        ev = ev || window.event;
        var target = ev.target || ev.srcElement;
        current = target.parentNode;
        dragging = true;
        x = ev.clientX;
        y = ev.clientY;
        Ox = current.offsetLeft;
        Oy = current.offsetTop;
        current.style.zIndex = ++enableDragging.z;

        document.onmousemove = function (ev) {
            ev = ev || window.event;
            pauseEvent(ev);
            if (dragging == true) {

                var Sx = ev.clientX - x + Ox,
                    Sy = ev.clientY - y + Oy;

                current.style.left = Math.max(Sx, Math.min(document.body.offsetWidth - Sx, 0)) + "px";
                current.style.top = Math.max(Sy, Math.min(document.body.offsetHeight - Sy, 0)) + "px";
                document.body.focus();
                document.onselectstart = function () {
                    return false;
                };
                ev.ondragstart = function () {
                    return false;
                };
                document.body.style.MozUserSelect = "none";
                document.body.style.cursor = "default";
                return false;
            }
        }
        document.ondragstart = function () {
            return false;
        }
        document.onmouseup = function (ev) {
            ev = ev || window.event;
            dragging && (dragging = false);
            if (ev.preventDefault) {
                ev.preventDefault();
            } else {
                e.cancelBubble = true;
                e.returnValue = false;
            }

            document.body.style.MozUserSelect = "text";
            document.body.style.cursor = "default";
            //toggleEnableSelectStart(true);
            return false;
        }
    };
}

我正在尝试设置边界,以使 div 不能拖到实际浏览器窗口的边界之外。

上面的函数完成了 50%,它不会让用户将 div 拖动到左上角和左边界之外。但是它让用户将其拖到底部和右侧之外..

任何想法如何解决这一问题?

4

1 回答 1

1

取您计算的值与窗口的宽度/高度边界减去 div 的宽度/高度之间的最小值:

current.style.left = Math.min(Math.max(Sx, Math.min(document.body.offsetWidth - Sx, 0)), document.body.offsetWidth - current.offsetWidth) + "px";
current.style.top = Math.min(Math.max(Sy, Math.min(document.body.offsetHeight - Sy, 0)), document.body.offsetHeight - current.offsetHeight) + "px";

编辑:

这些方面的东西(请注意,这写得很快,与你的格式不同!)

http://jsfiddle.net/WKLa7/1/

于 2013-03-03T20:14:05.147 回答