最近寫CSS3和js結合,遇到了很多次z-index不生效的情況:
1.在用z-index的時候,該元素沒有定位(static定位除外)
2.在有定位的情況下,該元素的z-index沒有生效,是因為該元素的子元素后來居上,蓋住了該元素,解決方式:將蓋住該元素的子元素的z-index設置為負數
下拉框例子:
1.蓋住的時候:

2.將下拉框的z-index設置為負數

代碼:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>無標題文檔</title> 6 <style type="text/css"> 7 * { 8 padding: 0; 9 margin: 0; 10 list-style: none; 11 } 12 .all { 13 width: 330px; 14 height: 120px; 15 overflow: hidden; 16 background: url(img/bg.jpg) no-repeat; 17 margin: 100px auto; 18 line-height: 30px; 19 text-align: center; 20 padding-left: 10px; 21 margin-bottom: 0; 22 } 23 .all ul { 24 position: relative; 25 height: 30px; 26 width: 100%; 27 } 28 .all ul li { 29 width: 100px; 30 height: 30px; 31 background: url(img/libg.jpg); 32 float: left; 33 margin-right: 10px; 34 position: relative; 35 cursor: pointer; 36 37 } 38 .all ul ul { 39 position: absolute; 40 left: 0; 41 top:-90px; 42 /*display: none; 是一瞬間的事*/ 43 transition: all 1s; 44 opacity: 0; 45 /*后來的盒子會蓋住前面的盒子,就算前面的盒子z-index再大也會被蓋住, 46 不過可以設置后來的盒子的z-index為負數就行了*/ 47 z-index:-1; 48 49 } 50 51 .all ul .lvTow { 52 top:-90px; 53 opacity: 0; 54 } 55 56 .all ul .show{ 57 top:30px; 58 opacity: 1; 59 } 60 61 </style> 62 </head> 63 64 <body> 65 <div class="all" id="list"> 66 <ul> 67 <li>一級菜單 68 <ul > 69 <li>二級菜單</li> 70 <li>二級菜單</li> 71 <li>二級菜單</li> 72 </ul> 73 </li> 74 <li>一級菜單 75 <ul > 76 <li>二級菜單</li> 77 <li>二級菜單</li> 78 <li>二級菜單</li> 79 </ul> 80 </li> 81 <li>一級菜單 82 <ul > 83 <li>二級菜單</li> 84 <li>二級菜單</li> 85 <li>二級菜單</li> 86 </ul> 87 </li> 88 </ul> 89 </div> 90 </body> 91 </html> 92 <script> 93 // 獲取對象 遍歷對象操作 顯示模塊 隱藏模塊 94 95 function List(id) { // 獲取對象 96 this.id = document.getElementById(id); 97 // 取 id 值 98 this.lis = this.id.children[0].children; // 獲取一級菜單所有的li 99 } 100 // init 初始化 101 List.prototype.init = function() { // 遍歷所有的li 顯示和隱藏 102 var that = this; 103 for(var i=0;i<this.lis.length;i++) 104 { 105 this.lis[i].index = i; 106 this.lis[i].onmouseover = function() { 107 that.show(this.children[0]); // 顯示出來 108 } 109 this.lis[i].onmouseout = function() { 110 that.hide(this.children[0]); // 隱藏起來 111 } 112 } 113 } 114 // 顯示模塊 115 List.prototype.show = function(obj) { 116 // obj.style.display = "block"; 117 obj.className = "show"; 118 119 } 120 // 隱藏模塊 121 List.prototype.hide = function(obj) { 122 // obj.style.display = "none"; 123 obj.className = "lvTow"; 124 } 125 var list = new List("list"); // 實例化了一個對象 叫 list 126 list.init(); 127 </script>
