自制模态框和关于z-index的知识

来源:互联网 发布:电子显微镜原理 知乎 编辑:程序博客网 时间:2024/04/23 14:10
<!DOCTYPE HTML>
<html style="height: 100%">
<head>
<meta charset="utf-8">
</head>
<body style="height: 100%;">
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<button id="one" type="button">click</button>
<div id="dialog" style="position: absolute;top:0px;left:0px;z-index: 1000;display: none;height: 100%;width: 100%;background-color: rgba(100,100,100,0.5);">
<div style="position: absolute;top: 30%;left: 50%;z-index: 1001;background-color:rgba(200,200,200,1);">
<div style="width: 400px;height: 400px;margin: 0px auto;">
hello
<div style="position: absolute;bottom: 0px;left: 45%">
<button type="button" id="ok">確定</button>
<button type="button">取消</button>
</div>
</div>


</div>


<div id="two"style="display:none;position: absolute;top: 20%;left: 40%;z-index: 1002;background-color:rgba(200,200,200,1);">
<div style="width: 400px;height: 400px;margin: 0px auto;">
world!
<div style="position: absolute;bottom: 0px;left: 45%">
<button type="button">確定</button>
<button type="button">取消</button>
</div>
</div>
</div>
</div>




<script type="text/javascript">
$(function() {
$("#one").click(function(){
$("#dialog").show()
})
$("#ok").click(function(){
$("#two").show()
})
})
</script>

</html>

点击click按钮的时候会弹出一个模态框,再次点击模态框里的确定按钮,也会弹出一个模态框,模态框的大致原理是利用pisition和z-index属性对元素进行堆叠,通过css的美化就可以生成我们想要的模态框,并且通过js的控制,我们可以定义模态框的各种行为,在这只是说一下大致的原理,有兴趣的可以自己研究一下。

下面说一下z-index,z-index这个属性需要在position和fixed定位下才有效,如果我们直接给body下的两个子元素设置z-index,是没有效果的。下面看看代码:

<!DOCTYPE HTML>
<html style="height: 100%">
<head>
<meta charset="utf-8">
</head>
<body style="height: 100%;">
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<div id="one" style="background-color: red;border: solid 1px red; position: absolute;top:0px;left:0px;z-index: 1;">

saaaaaaaaa

<span style="position: relative;z-index: 100">ssssssssssss</span>

</div>
<div id="two" style="background-color: green;border: solid 1px green; position: absolute;top:1px;left:1px;z-index: 2">

zzzzzzzzzzzzzzzz

<span style="position: relative;z-index: -100">ssssssssssss</span>

</div>
</html>

body下的两个div one two是处于一个等级的,他们通过z-index进行上下堆叠显示,因为two的z-index比较大,所以显示的时候会把one给覆盖,(通过设置定位使得两个元素重叠来看效果),但是one下面的子元素设置为100并不会使得span覆盖two,two下的子元素设置为-100也不会有效果,因为对于z-index的比较 ,是在同等级的元素下比较的,同等级的元素的子元素是无法比较的,因为two比onez-index大,所以two的z-index比one大,所以two下面的子元素不管设置z-index为多少,都会把one元素及其子元素覆盖,这可能就是所谓的拼爹效应,z-index的知识比较多,有兴趣的可以百度一下。

0 0
原创粉丝点击