在Web开发中, 经常需要弹出一个窗口. 你可能想到使用alert, confirm 或者 window.open, 不过可以用自定义的窗口. 方法是建立一个绝对定位的层, 添加到body节点中. 需要关闭时就将它先移除.
弹出一个窗口
配套的CSS样式表:
.popwindow{
font-family: monospace;
position: absolute;
padding: 0;
border: 1px solid #369;
background: #def;
}
.popwindow .head{
text-align: center;
padding: 2px;
background: #6cf;
border-bottom:1px solid #369;
}
.popwindow .closeButton{
float: right;
margin: 2px 4px;
font-weight: bold;
}
弹出一个窗口
/*
* 用来弹出一个窗口
*/
function openPopWindow(title, content, top, left, width, height){
var pop = document.createElement('div');
popId = 'pop_' + (new Date()).getTime();
pop.setAttribute('id', popId);
pop.setAttribute('class','popwindow');
pop.setAttribute('className','popwindow');
if(height > 0){
pop.style.height = height + 'px';
}
pop.style.width = width + 'px';
pop.style.display = 'block';
pop.style.top = top + 'px';
pop.style.left = left + 'px';
document.getElementsByTagName('body')[0].appendChild(pop);
pop.innerHTML =
'<div class="closeButton"><a href="javascript: closePopWindow(\'' + popId + '\');">X</a></div>'
+ '<div class="head">' + title + '</div>'
+ '<div class="content">' + content + '</div>';
return pop;
}
function closePopWindow(id){
var pop = document.getElementById(id);
document.getElementsByTagName('body')[0].removeChild(pop);
}
/*
* 使用方法:
*/
function popEditWindow(){
top = 100;
left = 100;
var text = '你好啊, 世界!';
openPopWindow('Hello world!', text, top, left, 220, -1);
}
配套的CSS样式表:
.popwindow{
font-family: monospace;
position: absolute;
padding: 0;
border: 1px solid #369;
background: #def;
}
.popwindow .head{
text-align: center;
padding: 2px;
background: #6cf;
border-bottom:1px solid #369;
}
.popwindow .closeButton{
float: right;
margin: 2px 4px;
font-weight: bold;
}