本章导读
目前,最流行的页面设计方法是div+iframe。div被称为层,是页面布局的常用控件。iframe被称为框架,可以用来在当前页面中嵌入其他页面。本章介绍了常见的div和iframe应用技巧。
5.1 div层提示效果
【实例描述】
当页面出现错误的时候,通常使用alert或者窗口给用户弹出错误信息,但这样会影响用户的操作。为了方便地显示错误信息,本例学习使用div层来显示错误信息。
【实现代码】
<script language=javascript>
var div_x,div_y;
function div6()
{
this.display=display;
}
//实现层和表格的动态创建
function display()
{
document.write("<table align=center><tr><td><button style='width:100px; height: 30px;font-size:12px;border:1px solid #A4B3C8;background-color:green;' type=button onclick=document.getElementById('div1').style.display='block' onfocus=this.blur()>div留言</button></td></tr></table>");
document.write("<div id='div1' style='font-size:12px;position:absolute; display: none;text-align:center;overflow:visible'>");
document.write("<div style='position:absolute;top:expression((body. clientHeight -300)/2);left:expression((body.clientWidth-200)/2);width:200px;height:180px;background-color:#dbdbdb;border:1px solid #cccccc;'>");
document.write("<table width=200 height=20 bgcolor=green onmousedown= 'div_x=event. x-parentNode.style.pixelLeft;div_y=event.y-parentNode.style.pixelTop;setCapture();' onmouseup='releaseCapture();' onmousemove='divMove(this. parentNode)' style='cursor:move;'>");
document.write("<tr align=center>");
document.write("<td align=left>提示:div6</td>");
document.write("</tr>");
document.write("</table>");
document.write("<span style= cursor:hand onclick=this.parentNode. parentNode.style. display='none';><br>发生了严重的错误...<br>[返回]</span>");
document.write(" </div>");
document.write("</div>");
}
//实现层的拖移
function divMove(obj)
{
if(event.button==1)
{
var divX=obj.clientLeft;
var divY=obj.clientTop;
obj.style.pixelLeft=divX+(event.x-div_x);
obj.style.pixelTop=divY+(event.y-div_y);
}
}
//创建并显示层
var mydiv=new div6();
mydiv.display();
</script>
【运行效果】
错误提示界面如图5-1所示,单击“返回”按钮,此提示会自动消失,还可以通过拖动提示消息的标题栏,实现div层的移动。

图5-1 错误提示界面
【难点剖析】
本例的重点是div层的动态创建和控制。使用“document.write”动态创建层,然后使用样式的“style.display”属性来控制层的隐藏或显示。当“style.display”的值为“none”时隐藏层,为“block”时显示层。






