首页 > 解决方案 > 如何在 CSS 中隐藏列表后面的内容?

问题描述

我的目标是将一些内容隐藏在将通过 jQuery 打开/关闭的列表后面。目前,当列表显示时,它会将所有内容下推。但是,我希望它显示为就像它上面的一层一样。我阅读了一些文章并考虑使用z-index. 虽然一旦我尝试使用它,它就无法正常工作。

$(document).ready(function() {
  $("#myList").toggle();

  $("#myInput").on("focus", function() {
    $("#myList").toggle();
  });

  $("#myInput").on("focusout", function() {
    // Here, it'll wait 100 miliseconds to hide the list.
    setTimeout(function() {
      $("#myList").toggle();
    }, 100);
  });

  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();

    $("#myList li").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });

  // This is the code to populate the field after selecting an option.
  $("#myList li").on("click", function() {
    var texto = $(this).text();
    $("#myInput").val(texto);
  });
});
.filter-search {
   width: 40%;

}

.list-group {
   z-index: 1;
}

.box{
	width:100px;
    height:100px;
}
 
.red{
	background:#f00;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="container">
  <h2>Filterable List</h2>
  <p>Type something in the input field to search the list for specific items:</p>  
  <div class="filter-search">
    <input class="form-control" id="myInput" type="text" placeholder="Search..">
    <br>
    <div class="list-group" id="myList">
      <a href="#" class="list-group-item list-group-item-action">Cras justo odio</a>
      <a href="#" class="list-group-item list-group-item-action">Dapibus ac facilisis in</a>
      <a href="#" class="list-group-item list-group-item-action">Morbi leo risus</a>
      <a href="#" class="list-group-item list-group-item-action">Porta ac consectetur ac</a>
      <a href="#" class="list-group-item list-group-item-action">Vestibulum at eros</a>
    </div> 
  </div>
  <div class="box red"></div>

</div>

标签: javascriptjquerycss

解决方案


你可以这样做:

.list-group {
  position: absolute;
}

推荐阅读