最近写CSS3和js结合,遇到了很多次z-index不生效的情况:
1.在用z-index的时候,该元素没有定位(static定位除外)
2.在有定位的情况下,该元素的z-index没有生效,是因为该元素的子元素后来居上,盖住了该元素,解决方式:将盖住该元素的子元素的z-index设置为负数
下拉框例子:
1.盖住的时候:
2.将下拉框的z-index设置为负数
代码:
无标题文档* {
padding: 0;
margin: 0;
list-style: none;
}
.all {
width: 330px;
height: 120px;
overflow: hidden;
background: url(img/bg.jpg) no-repeat;
margin: 100px auto;
line-height: 30px;
text-align: center;
padding-left: 10px;
margin-bottom: 0;
}
.all ul {
position: relative;
height: 30px;
width: 100%;
}
.all ul li {
width: 100px;
height: 30px;
background: url(img/libg.jpg);
float: left;
margin-right: 10px;
position: relative;
cursor: pointer;
}
.all ul ul {
position: absolute;
left: 0;
top:-90px;
/*display: none; 是一瞬间的事*/
transition: all 1s;
opacity: 0;
/*后来的盒子会盖住前面的盒子,就算前面的盒子z-index再大也会被盖住,
不过可以设置后来的盒子的z-index为负数就行了*/
z-index:-1;
}
.all ul .lvTow {
top:-90px;
opacity: 0;
}
.all ul .show{
top:30px;
opacity: 1;
}
- 一级菜单
- 二级菜单
- 二级菜单
- 二级菜单
- 一级菜单
- 二级菜单
- 二级菜单
- 二级菜单
- 一级菜单
- 二级菜单
- 二级菜单
- 二级菜单
// 获取对象 遍历对象操作 显示模块 隐藏模块
function List(id) { // 获取对象
this.id = document.getElementById(id);
// 取 id 值
this.lis = this.id.children[0].children; // 获取一级菜单所有的li
}
// init 初始化
List.prototype.init = function() { // 遍历所有的li 显示和隐藏
var that = this;
for(var i=0;i
{
this.lis[i].index = i;
this.lis[i].onmouseover = function() {
that.show(this.children[0]); // 显示出来
}
this.lis[i].onmouseout = function() {
that.hide(this.children[0]); // 隐藏起来
}
}
}
// 显示模块
List.prototype.show = function(obj) {
// obj.style.display = "block";
obj.className = "show";
}
// 隐藏模块
List.prototype.hide = function(obj) {
// obj.style.display = "none";
obj.className = "lvTow";
}
var list = new List("list"); // 实例化了一个对象 叫 list
list.init();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。