可以拖动的DIV层
此篇文章是 希恩 在 发表的,所在栏目:HTML&CSS,应用标签:none。

CSS

.dragWindow{
min-width:300px;
min-height: 240px;
position: absolute;
z-index: 9999;
}

HTML

<div class="dragWindow" style="width: 320px">
    可拖动窗口
</div>

JS

(function($){
window.dwInit = function (){
    $.dw = document.querySelector('.dragWindow');
    if(!$.dw){
        console.log('drag-window 未启用');
        return;
    }
    console.log('drag-window 已启用');
    //判断鼠标是否按下
    $.p = false;
    //鼠标按下处在页面中的水平偏移
    $.dx = 0;
    //鼠标按下处在页面中的垂直偏移
    $.dy = 0;
    //div在页面中的水平偏移
    $.sx = 0;
    //div在页面中的垂直偏移
    $.sy = 0;

    //鼠标按下时
    $.dw.onmousedown = function(e){
        if (!$.p) {
            $.p = true;
        }
        //处理兼容性和滚动条
        let event = e || window.event;
        let scrollLeft = document.documentElement.scrollLeft;
        let scrollTop = document.documentElement.scrollTop;
        let pageX = event.pageX || event.clientX + scrollLeft;
        let pageY = event.pageY || event.clientY + scrollTop;
        $.dx = pageX;
        $.dy = pageY;
        $.sx = $.dw.offsetLeft;
        $.sy = $.dw.offsetTop;
    }

    //鼠标移动时
    document.onmousemove = function(e){
        if ($.p) {
            let event = e || window.event;
            let scrollLeft = document.documentElement.scrollLeft;
            let scrollTop = document.documentElement.scrollTop;
            let pageX = event.pageX || event.clientX + scrollLeft;
            let pageY = event.pageY || event.clientY + scrollTop;
            $.dw.style.left = pageX - ($.dx - $.sx) + 'px';
            $.dw.style.top = pageY - ($.dy - $.sy) + 'px';
        }
    }

    //鼠标松开时
    document.onmouseup = function(){
        if ($.p) {
            $.p = false;
        }
    }
    window.dragWindow = $;
}

})({})

初始化

initDw(){
            let si = setInterval(function(){
                if (window.dwInit) {
                    clearInterval(si);
                    dwInit();
                }
            })
        }

暂无评论
这儿空空的,快来说两句吧!

发表评论

icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif
© 2022 SHEAN.
本站由 Typecho 强力驱动.
请勿转载本站原创内容,