【问题标题】:How to layer multiple elements on top of one another?如何将多个元素叠加在一起?
【发布时间】:2022-01-14 14:12:15
【问题描述】:
<div class="parent">
  <div class="child" id="child-A">
  <div class="child" id="child-B">
  <div class="child" id="child-C">
</ div>

所以这个想法是,最初,child-A 将在顶部,这意味着 child-Bchild-C 将不可见,因为它们将在底部,被 child-A 覆盖/屏蔽。

所以会有一个切换开关,缩小每个孩子的宽度,以设置谁是可见的,谁是隐藏的。

【问题讨论】:

  • z-index 是您要找的吗?
  • 它应该是某种position 属性。

标签: javascript html css reactjs


【解决方案1】:

const checkboxes = document.querySelectorAll( 'input[type=checkbox]' );

var myFunction = function( event ) {
    var attribute = event.target.getAttribute("data-target");
    var element = document.getElementById(attribute);
    if (element.style.display === "none")
    element.style.display = "block";
    else 
    element.style.display = "none";
};

for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('change', myFunction, false);
}
.child{
width:200px;
height:200px;
position:absolute;
}

#child-A{
background:red;
z-index:100;
}

#child-B{
background:blue;
z-index:99;
}

#child-C{
background:yellow;
z-index:98;
}

#controls{
margin-left: 210px;
}
<div class="parent">
  <div class="child" id="child-A"></div>
  <div class="child" id="child-B"></div>
  <div class="child" id="child-C"></div>
</div>

<div id="controls">
<label><input type="checkbox" data-target="child-A" checked/> Child A </label> <br>
<label><input type="checkbox" data-target="child-B" checked/> Child B </label> <br>
<label><input type="checkbox" data-target="child-C" checked/> Child C </label> <br>
</div>

【讨论】:

    【解决方案2】:

    您可以通过使用 css positionz-index 来实现您的目标,并且为了打开活动,您可以通过 JS 改变项目的类。这里是一个简单的例子,点击黑色区域,激活的就会改变。

    let i = 0;
    const children = document.querySelectorAll('.child');
    
    function toggleDiv() {
      children[i].classList.remove('active');
      i = (i + 1) % 3; //since we have 3 child
      children[i].classList.add('active');
    }
    .child {
      position: absolute;
      height: 100px;
      width: 100px;
      font-size: 20px;
      background: black;
      color: white;
    }
    
    .child.active {
      z-index: 1;
    }
    <div class="parent" onClick="toggleDiv()">
      <div class="child active" id="child-A">child-A</div>
      <div class="child" id="child-B">child-B</div>
      <div class="child" id="child-C">child-C</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      相关资源
      最近更新 更多