自定义div可拖动功能 - 窗口边界?

时间:2013-03-03 20:05:20

标签: javascript

我使用以下函数通过句柄拖动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拖到左上角和左上角之外。然而,它让用户将其拖到底部和右侧..

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

1 个答案:

答案 0 :(得分: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/