在工作过程中经常遇到做弹出的层效果,有的需要在元素右下弹出,有的需要弹出在浏览器正中间,有的需要弹出后再拖拽,有的需要背景要变暗,有的需要弹出的层跟随鼠标移动……
网上此类效果其实很多,有javascript原生的,有基于框架写的,但自己好多时候用不到那么高级的效果,所以就把这些功能都分开来一步一步实现。
其实原理很简单.有两种实现途径:一种是通过元素创建和删除,一种是通过显示和隐藏,其余的具体要做成什么样子,就留给CSS来控制了。下面从最简单的开始(不基于框架)
一、最简单的弹出
用到的javascript代码如下:
function show(){
var oShow = document.getElementById('show');
oShow.style.display = 'block';
var oClose = document.createElement("span");
oClose.innerHTML = "";
oShow.appendChild(oClose);
oClose.onclick = function(){
oShow.style.display = 'none';
oShow.removeChild(this);
}
}
function show(){
var iWidth = document.documentElement.clientWidth; //获取浏览器宽度
var iHeight = document.documentElement.clientHeight; //获取浏览器高度
var oShow = document.getElementById('show');
oShow.style.display = 'block';
oShow.style.left = (iWidth-302)/2+"px"; //居中横坐标
oShow.style.top = (iHeight-202)/2+"px"; //居中纵坐标
var oClose = document.createElement("span");
oClose.innerHTML = "";
oShow.appendChild(oClose);
oClose.onclick = function(){
oShow.style.display = 'none';
oShow.removeChild(this);
}
}
function show(){
var iWidth = document.documentElement.clientWidth;
var iHeight = document.documentElement.clientHeight;
var bgObj = document.createElement("div"); //创建背景层
bgObj.setAttribute("id","bgbox");
bgObj.style.width = iWidth+"px";
bgObj.style.height =Math.max(document.body.clientHeight, iHeight)+"px";
document.body.appendChild(bgObj); //将创建的层插入body中
var oShow = document.getElementById('show');
oShow.style.display = 'block';
oShow.style.left = (iWidth-302)/2+"px";
oShow.style.top = (iHeight-202)/2+"px";
var oClosebtn = document.createElement("span");
oClosebtn.innerHTML = "";
oShow.appendChild(oClosebtn);
function oClose(){
oShow.style.display = 'none';
oShow.removeChild(oClosebtn);
document.body.removeChild(bgObj);
}
oClosebtn.onclick = oClose;
bgObj.onclick = oClose;
}
function getEvent(){
return window.event || arguments.callee.caller.arguments[0];
// 获得事件Event对象,用于兼容IE和FireFox
}
document.onkeyup = function(){
var event = getEvent();
if (event.keyCode == 27){
oClose();
}
}
var moveX = 0;
var moveY = 0;
var moveTop = 0;
var moveLeft = 0;
var moveable = false;
var docMouseMoveEvent = document.onmousemove;
var docMouseUpEvent = document.onmouseup;
titleBar = document.getElementById('titlebar');
titleBar.onmousedown = function() {
var evt = getEvent();
moveable = true;
moveX = evt.clientX;
moveY = evt.clientY;
moveTop = parseInt(oShow.style.top);
moveLeft = parseInt(oShow.style.left);
document.onmousemove = function() {
if (moveable) {
var evt = getEvent();
var x = moveLeft + evt.clientX - moveX;
var y = moveTop + evt.clientY - moveY;
if ( x > 0 &&( x + 302 < iWidth) && y > 0 && (y + 202 < iHeight) ) {
oShow.style.left = x + "px";
oShow.style.top = y + "px";
}
}
};
document.onmouseup = function () {
if (moveable) {
document.onmousemove = docMouseMoveEvent;
document.onmouseup = docMouseUpEvent;
moveable = false;
moveX = 0;
moveY = 0;
moveTop = 0;
moveLeft = 0;
}
};
}
有话要说