Fork me on GitHub

pc端拖拽

var move=document.getElementsByClassName("page1_2")[0];
    var startX=0;
    var startY=0;
    var x=0;
    var y=0;
    var off = 0;

    move.onmousedown=function (e) {
        var e = e || event;
        off=1;
        startX = this.offsetLeft;
        startY = this.offsetTop;
        x=e.pageX-startX;
        y=e.pageY-startY;

    };

    document.onmousemove=function (e) {
        var e = e || event;
        if (!off)return;
        var x1=e.pageX-x;
        var y1=e.pageY-y;
        if(x1<0){
            x1=0
        }
        if(y1<0){
            y1=0
        }
        if(x1>window.innerWidth-move.offsetWidth){
            x1=window.innerWidth-move.offsetWidth
        }
        if(y1>window.innerHeight-move.offsetHeight){
            y1=window.innerHeight-move.offsetHeight
        }
        move.style.left=x1+'px';
        move.style.top=y1+"px";
};

        document.onmouseup=function (e) {
            off = 0;
        };

 

window.onload=function(){
            var q1=document.getElementById('q1');
            var disx=0;
            var disy=0;
            q1.onmousedown=function(ev){
                var oEvent=ev||event;
                disx=oEvent.clientX-q1.offsetLeft;
                disy=oEvent.clientY-q1.offsetTop;
                document.onmousemove=function(ev){
                    var oEvent=ev||event;
                    var l=oEvent.clientX-disx;
                    var t=oEvent.clientY-disy;
                    if(l<0){
                        l=0
                    }else if(l>document.documentElement.clientWidth-q1.offsetWidth){
                        l=document.documentElement.clientWidth-q1.offsetWidth
                    }
                    if(t<0){
                        t=0
                    }
                    else if(t>document.documentElement.clientHeight-q1.offsetHeight){
                        t=document.documentElement.clientHeight-q1.offsetHeight
                    }
                    q1.style.left=l+'px';
                    q1.style.top=t+'px';

                };
                document.onmouseup=function(){
                    document.onmousemove=null;
                    document.onmouseup=null;
                }

            };
            return false;//阻止默认行为,火狐浏览器第二次拖拽有空div
        }

 

posted @ 2017-09-06 18:48  小白不白10  阅读(201)  评论(0编辑  收藏  举报