厌烦了JS的Alert,非常想自己写一个弹出层的JS,苦于水平和时间,久时未成。近日,自觉水平有所升,时间略宽裕,写之,以飨你我。思路大体如下:
1、需要创建两个层,一层遮罩,一层显示。
2、显示的层中需要有以下几个DIV:标题、关闭和信息提示区。
3、然后就是CreateElement,设置各个DIV的CSS,需要注意JS在使用CSS的值时还是有一定规律的,例如z-Index,需要改为为zIndex,font-size在使用时为fontSize,也就是说凡是中间有短线的,去掉短线,然后把短线后的属性首字符大写即可。有一个Float需要特别注意,在IE下为styleFloat,其它环境中为cssFloat。
使用的时候引入JS文件,调用时用myopen('消息内容',宽度,高度)即可。例如:myopen('你的回答太对了',300,150);对于看够了alert的人来说,偶而用一下,效果也还是不错的。使用的时候还是比较方便的,毕竟只有一个JS文件。
var body=document.compatMode=="CSS1Compat"?document.documentElement:document.body;
var slj_popwin=document.createElement("div");
var slj_showwin=document.createElement("div");
var slj_title=document.createElement("div");
var slj_showmsg=document.createElement("div");
var slj_close=document.createElement("div");
document.getViewHeight = function(){
if (window.innerHeight!=window.undefined) return window.innerHeight;
if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
if (document.body) return document.body.clientHeight;
return window.undefined;
}
document.getViewWidth = function(){
if (window.innerWidth!=window.undefined) return window.innerWidth;
if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth;
if (document.body) return document.body.clientWidth;
return window.undefined;
}
function $(Id) { return document.getElementById(Id); }
function center(win,w,h)
{
var s = win.style;
s.left = (document.getViewWidth()-w)/2+"px";
s.top = (document.getViewHeight()-h)/2+"px";
}
function myopen(str,w,h){
with(body.style)
{
width=document.getViewWidth()+"px";
height=document.getViewHeight()+"px";
}
with(slj_popwin.style)
{
width=document.getViewWidth()+"px";
height=document.getViewHeight()+"px";
display="block";
background="#ccc";
top="0px";
left="0px";
position="absolute";
// filter=alpha(opacity=90);
opacity=0.9;
zIndex=2;
overflow="hidden";
}
with(slj_showwin.style)
{
position="absolute";
background="#297405";
zIndex=3;
display="block";
overflow="hidden";
width=w+"px";
height=h+"px";
}
with(slj_title.style)
{
position="relative";
background="#90be4a";
styleFloat="left";
zIndex=3;
display="block";
overflow="hidden";
width="300px";
height="20px";
}
with(slj_showmsg.style)
{
position="relative";
textAlign="center";
top="50px";
fontSize="12px";
zIndex=3;
display="block";
overflow="hidden";
width="300px";
height="20px";
}
with(slj_close.style)
{
position="relative";
padding="5px";
styleFloat="right";
fontSize="12px";
}
body.appendChild(slj_popwin);
body.appendChild(slj_showwin);
slj_showwin.appendChild(slj_title);
slj_title.appendChild(slj_close);
slj_showwin.appendChild(slj_showmsg);
slj_showmsg.id="slj_showmsg";
slj_showwin.id="slj_showwin";
slj_close.id="slj_close";
$("slj_close").innerHTML="<a href=\"#\" onClick=\"Close();\" style=\"text-decoration:none;\">关闭</a>";
$("slj_showmsg").innerHTML="<font color=\"red\">"+str+"</font>";
center($("slj_showwin"),w,h);
}
function Close()
{
body.removeChild(slj_popwin);
body.removeChild(slj_showwin);
window.location.reload();
}