1. 程式人生 > >仿百度首頁登陸框拖拽效果(可視視窗內拖動)

仿百度首頁登陸框拖拽效果(可視視窗內拖動)

            window.onload = function() {                //獲取函式物件                function G(id) {                    return document.getElementById(id);                }                function autocenter(el) {                    var bodyW = document.documentElement.clientWidth;                    var bodyH = document.documentElement.clientHeight;                    var
elW = el.offsetWidth;                    var elH = el.offsetHeight;                    el.style.left = (bodyW - elW) / 2 + "px";                    el.style.top = (bodyH - elH) / 2 + "px";                }                var mouseoffsetX = 0;                var mouseoffsetY = 0;                var isdrag = false
;                G('title').onmousedown = function(e) {                    var e = e || window.event;                    mouseoffsetX = e.pageX - G('login').offsetLeft;                    mouseoffsetY = e.pageY - G('login').offsetTop;                    isdrag = true; //可拖動標誌位                };                document.onmousemove = function
() {
                    var e = e || window.event;                    var mouseX = e.pageX; //滑鼠當前位置                    var mouseY = e.pageY;                    var moveX = 0; //滑鼠新位置                    var moveY = 0;                    if(isdrag == true) {                        moveX = mouseX - mouseoffsetX;                        moveY = mouseY - mouseoffsetY;                        //範圍限定 moveX>0&&moveX<(頁面寬度-浮層寬度)                        //範圍限定 moveY>0&&moveX<(頁面高度-浮層高度)                        var bodyW = document.documentElement.clientWidth;                        var bodyH = document.documentElement.clientHeight;                        var elW = G('login').offsetWidth;                        var elH = G('login').offsetHeight;                        var maxX = bodyW - elW; //left最大值                        var maxY = bodyH - elH; //top最大值                        moveX = Math.min(maxX, Math.max(0, moveX)); //這兩句是精華                        moveY = Math.min(maxY, Math.max(0, moveY));                        G('login').style.left = moveX + "px";                        G('login').style.top = moveY + "px";                    }                }                document.onmouseup = function() {                    isdrag = false;                }                G('lg').onclick = function() {                    G('mask').style.display = "block";                    G('login').style.display = "block";                    autocenter(G('login'));                }                G('close').onclick = function() {                    G('mask').style.display = "none";                    G('login').style.display = "none";                }                window.onresize = function() {                    autocenter(G('login'));                }            }