前端杂记

弹框拖动功能 && mouseup事件丢失

2019-05-15  本文已影响0人  muroujue

对于某区域的拖动功能主要用到mousedown,mousemove和mouseup事件,具体代码如下:

function pauseEvent(e){
    if(e.stopPropagation) e.stopPropagation();
    if(e.preventDefault) e.preventDefault();
    e.cancelBubble=true;
    e.returnValue=false;
    return false;
}
$('.selectMajor .co_tit').mousedown(function(ev){
    var e = ev||event;
    pauseEvent(e);
    var mdX = e.clientX;
    var mdY = e.clientY;
    var ele_top = $('.selectMajor').position().top;
    var ele_left = $('.selectMajor').position().left;
    var ele_width = $('.selectMajor').width();
    var ele_height = $('.selectMajor').height();
    var win_width = $(window).width();
    var win_height = $(window).height();
    // IE8 取消默认行为-设置全局捕获
    if ($('.selectMajor .co_tit').setCapture) {
        $('.selectMajor .co_tit').setCapture();
    }
    document.onmousemove = function(ev2) {
        var e2 = ev2||event;
        pauseEvent(e2);
        var mmX = e2.clientX;
        var mmY = e2.clientY;
        var moveX = mmX-mdX;
        var moveY = mmY-mdY;
        var target_top = ((ele_top+moveY) > (win_height-ele_height)) ? (win_height-ele_height) : (ele_top+moveY)
        target_top = target_top < 0 ? 0 : target_top
        var target_left = (ele_left+moveX-400) < 0 ? 400 : ( (ele_left+moveX-400)>(win_width-ele_width) ? (win_width-ele_width+400) : ele_left+moveX )
        $('.selectMajor').css('top',target_top+'px');
        $('.selectMajor').css('left',target_left+'px');
    }
})
document.onmouseup = function() {
    document.onmousemove = null;
    // 释放全局捕获
    if ($('.selectMajor .co_tit').releaseCapture) {
        $('.selectMajor .co_tit').releaseCapture();
    }
}

在测试时会发现,如果不加pauseEvent方法时,会出现时常mouseup事件丢失的情况。具体原因:

加的pauseEvent方法就是用来防止触发drag操作的。

上一篇下一篇

猜你喜欢

热点阅读