CSS3过渡和z-index

3

我正在处理我的项目,但在CSS中遇到了z-index的问题。我已经搜索了一整天,但没有找到适合我的解决方案。问题是,我得到了一个div在另一个div下面。这必须与z-index有关。希望有人能找出我做错了什么...

$(".box").click(function() {
  $(this).css({
    "-webkit-transform-style": "preserve-3d",
    "background-color": "red",
    "box-shadow": "0px 0px 10px red",
    "-webkit-transition:": "all .2s ease-in",
    "zoom": "1",
    "z-index": "10",
    "-webkit-transform": "rotateY(0deg)"
  });

  $(this).mouseleave(function() {
    $(this).css({
      "-webkit-transform-style": "preserve-3d",
      "background-color": "blue",
      "box-shadow": "",
      "-webkit-transition:": "all .2s ease-out",
      "zoom": "",
      "z-index": "1",
      "-webkit-transform": "rotateY(45deg)"
    });
  });
});
#blue {
  -webkit-perspective: 600px;
}
#blue .box {
  position: absolute;
  zoom: 0.7;
  background-color: blue;
  -webkit-transform: rotateY(45deg);
  -webkit-transition: all .2s ease-out;
  z-index: 0;
  height: 100px;
  width: 200px;
  margin-left: 50px;
  margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="blue" class="container" style="margin-left: 50px">
  <div class="box" id="first"></div>
</div>
<div id="blue" class="container" style="margin-left: 200px">
  <div class="box" id="second"></div>
</div>

I have also putted all together in jsFiddle

1个回答

2

你的问题是由父元素(.container)引起的。因为它们的html顺序以及它们的静态定位,第二个.container的子元素将始终在第一个.container的前面。

如果你必须使用这种html结构,请在.container默认css中添加“position:relative”,并在事件中单独调整它们的z-index。

#blue {
    position:relative;
}

$(".box").click(function () {
    $(this).css({"-webkit-transform-style":"preserve-3d",
                 "background-color":"red",
                 "box-shadow":"0px 0px 10px red",
                 "-webkit-transition":"all .2s ease-in",
                 "zoom":"1",
                 "z-index":"10",
                 "-webkit-transform":"rotateY(0deg)"});

    this.parentNode.style.zIndex = '1';

        $(this).mouseleave(function() {
        $(this).css({"-webkit-transform-style":"preserve-3d",
                     "background-color":"blue",
                     "box-shadow":"",
                     "-webkit-transition:":"all .2s ease-out",
                     "zoom":"",
                     "z-index":"1",
                     "-webkit-transform":"rotateY(45deg)"});

         this.parentNode.style.zIndex = '0';

       });
    });

http://jsfiddle.net/aPKh6/10/

此外,不应在多个元素上使用id。这是无效的,并且它还限制了您使用JavaScript进行更有效的元素选择的能力。

当您将事件侦听器嵌套在另一个侦听器函数中时,还存在同时触发多个事件的可能性,但我不知道jQuery是否会为您处理此问题。我总是发现最好分别声明它们,并使用标志来查看是否先触发了一个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接