堆栈更大的z-index不在元素的前面?

时间:2017-04-03 22:47:15

标签: jquery css

我目前的困惑是,即使我为div标签设置了更大的z-index值,在操作一些CSS之后它也不再是顶部了。

代码使用如下:

$('.lights').on('click',function(){
  $('<div id="lightsOut"></div>').appendTo('body');
  
  $('#lightsOut').css( { 
  	opacity: 0, 
    width: $(document).width(), 
    height: $(document).height() 
  } )
    .addClass('lightsOut')
    .animate({opacity: 1}, 400);
    
  $('#media').css( { "z-index": "10000" } );
});
.lightsOut {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 0px;
  height: 0px;
  background-color: #000;
  z-index: 9999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h4>Title</h4>
<div id="media">
  <button class="lights">Lights Out</button>
  <h4 style="color: grey">Another Title</h4>
</div>
</body>

单击“div media”元素时,我想将背景更改为黑色,同时仍显示“div media”元素。我怎样才能实现这种行为?

1 个答案:

答案 0 :(得分:0)

申请positoin亲戚

$('#media').css( { "position": "relative" } );

下面的代码段

&#13;
&#13;
$('.lights').on('click',function(){
  $('<div id="lightsOut"></div>').appendTo('body');
  
  $('#lightsOut').css( { 
  	opacity: 0, 
    width: $(document).width(), 
    height: $(document).height() 
  } )
    .addClass('lightsOut')
    .animate({opacity: 1}, 400);
    
  $('#media').css( { "z-index": "10000" } );
    $('#media').css( { "position": "relative" } );
});
&#13;
.lightsOut {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 0px;
  height: 0px;
  background-color: #000;
  z-index: 9999;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h4>Title</h4>
<div id="media">
  <button class="lights">Lights Out</button>
  <h4 style="color: grey">Another Title</h4>
</div>
</body>
&#13;
&#13;
&#13;