0

我正在使用以下函数来拖动 div:

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

        var viewportWidth = viewport().width;
        var viewportHeight = viewport().height;
        document.onmousemove = function (ev) {
            ev = ev || window.event;
            if (dragging == true) {
                var Sx = parseFloat(ev.clientX) - x + Ox;
                var Sy = parseFloat(ev.clientY) - y + Oy;
                current.style.left = Math.min(Math.max(Sx, Math.min(viewport().width - Sx, 0)), viewportWidth - current.offsetWidth) + "px";

                current.style.top = Math.min(Math.max(Sy, Math.min(viewport().height - Sy, 0)), viewportHeight - current.offsetHeight) + "px";
            }
        }

        document.onselectstart = function () {
            return false;
        };

        document.onmouseup = function (ev) {
            ev = ev || window.event;
            dragging && (dragging = false);
            if (ev.preventDefault) {
                ev.preventDefault();
            }
        }

        document.body.style.MozUserSelect = "none";
        document.body.style.cursor = "default";

        return false;
    };
}

function viewport() {
    var e = window
    , a = 'inner';
    if ( !( 'innerWidth' in window ) ) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}

这就是我开始拖动的方式:

        var ele = document.getElementById("snapifyWrapper");
        enableDragging(ele, 'hndl');

我想弄清楚如何让阻力变慢?基本上我想减慢 div 被拖动的速度

4

1 回答 1

0

在您的document.onmousemove()功能中,也许检查它Sx并且与移动对象之前和之前Sy有足够的不同?xycurrent

因此,在移动对象之前指定一个阈值并与该阈值进行比较。

// need to have displacement of 10px before moving the object
var threshold = 10;   
var getAbs = Math.abs;    // local reference to Math.abs() function
document.onmousemove = function (ev) {
    ev = ev || window.event;
    if (dragging == true) {
        var Sx = parseFloat(ev.clientX) - x + Ox;
        var Sy = parseFloat(ev.clientY) - y + Oy;

        if (getAbs(Sx) > threshold || getAabs(Sy) > threshold) {
            // move it       
            current.style.left = Math.min(Math.max(Sx, Math.min(viewport().width - Sx, 0)), viewportWidth - current.offsetWidth) + "px";
            current.style.top = Math.min(Math.max(Sy, Math.min(viewport().height - Sy, 0)), viewportHeight - current.offsetHeight) + "px";
        }
    }
}

您还可以添加一个来指定mousemovetimer应该在多长时间之前记录坐标。

于 2013-03-20T08:53:31.167 回答