0

我使用以下函数来拖动带有句柄的 div。

问题是,在某些浏览器中,当我同时拖动文本时,文本被选中并在页面上突出显示..

任何想法如何解决它?

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

        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.top = Sy + "px";
                current.style.left = Sx + "px";
                document.body.focus();
                // prevent text selection in IE
                document.onselectstart = function () { return false; };
                // prevent IE from trying to drag an image
                ev.ondragstart = function() { return false; };                  
                return false;   
            }
        }
        document.onmouseup = function(ev) {
            //alert("stop");
            dragging && (dragging = false);
        }
    };
}    

function pauseEvent(e){
    if(e.stopPropagation) e.stopPropagation();
    if(e.preventDefault) e.preventDefault();
    e.cancelBubble=true;
    e.returnValue=false;
    return false;
}

拖动开始于:

    var ele = document.getElementById("divWrapper");
    enableDragging(ele);
4

1 回答 1

0

对不起,我忘记了你上一篇文章中的第二个问题。但是,您也需要防止默认onmouseup

document.onmouseup = function(ev) {
    ev = ev || window.event;
    dragging && (dragging = false);
    if (ev.preventDefault) {
        ev.preventDefault();
    } else {
        ev.cancelBubble=true;
        ev.returnValue=false;
    }
    return false;
}

编辑

或者干脆使用你的pauseEvent()功能。请注意,在您的代码中有这样的:ev.ondragstart = function () {...};. 将事件处理程序分配给 Event 对象是没有用的,而是将其分配给documentor document.body。并且也在pauseEvent()每个事件处理函数中使用它。

看起来最好移动到处document.onselectstart​​理document.ondragstart程序onmousedown,因为当执行移动到onmousemove().

于 2013-02-10T19:38:00.047 回答