Home > Enterprise >  How to layer multiple elements on top of one another?
How to layer multiple elements on top of one another?

Time:12-10

<div >
  <div  id="child-A">
  <div  id="child-B">
  <div  id="child-C">
</ div>

So the idea is that initially, child-A will be on top, meaning child-B and child-C won't be visible because they will be on the bottom, covered / shielded by child-A.

So there will be a toggle that shrinks the width of each child to set who is visible and who is hidden.

CodePudding user response:

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 >
  <div  id="child-A"></div>
  <div  id="child-B"></div>
  <div  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>

CodePudding user response:

You can acheive your goal by using css position and z-index, and in order to toggle the active on, you can mutate item's class by JS. Here is an simple example, by clicking on the black area, the active on will be change.

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  onClick="toggleDiv()">
  <div  id="child-A">child-A</div>
  <div  id="child-B">child-B</div>
  <div  id="child-C">child-C</div>
</div>

  • Related