拖动div选择页面上的文本(某些浏览器)

时间:2013-02-10 19:25:01

标签: javascript

我使用以下函数拖动带手柄的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);

1 个答案:

答案 0 :(得分: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对象没有用,而是将其分配给documentdocument.body。并且在每个eventhandler函数中也使用pauseEvent()

document.onselectstartdocument.ondragstart移到onmousedown处理程序似乎更好,因为当执行转移到onmousemove()时,这些事件已经被触发。