在点击时切换Z索引更改vanillaJS

问题描述

我正在尝试更改香草JS上单击的项目的z-index。 当发生点击事件时,被点击的项目应该位于最前面。只有两个div atm,但还会有更多。 我存储的是最后点击的项目,因此,如果发生新的点击事件,则最后点击的项目的Z索引会更少。但这似乎不起作用(两个项目都是相对位置的) 任何帮助将不胜感激。

<div class="post" data-name="post" draggable="true">1</div>
<div class="post" data-name="post" draggable="true">2</div>
const a = new A()

memoSection.addEventListener('click',({target})=>{
    switch(target.dataset.name){
          case "post":
                let clickedItem ="";
                a.bringFront(clickedItem)
                break;
})
class A{
    constructor(){
        this.selected = null
    }


    bringFront(clickedItem){
        this.selected = clickedItem; //store the prevIoUsly clicked element
        if(!clickedItem.style.zIndex == 10 || !clickedItem.style.zIndex){
            this.selected.zIndex = 0
            clickedItem.style.zIndex = 10
        } else { 
            this.selected.zIndex = 10
            clickedItem.style.zIndex = 0 }
    }

}

解决方法

我不明白您的代码正在尝试做什么,但这是示例,如何获得预期的效果:

document.querySelectorAll('.post').forEach(item => {
//get all elements with class .post

  item.addEventListener('click',event =>  {
  // add Event Listener to each
    document.querySelectorAll('.post').forEach(el => {
      el.style.zIndex = "0";
    })
    // when clicked fetch all again and set all back to 0

    item.style.zIndex = "10";
    //set clicked only to 10
    console.clear()
    console.log(item.innerHTML);

  })
})
.post:first-of-type {
  position: absolute;
  background-color: blue;
  left: 100px;
  top: 50px;
  width: 150px;
  height: 150px;
  z-index: 0;
}

.post {
  position: absolute;
  background-color: red;
  left: 25px;
  top: 50px;
  width: 150px;
  height: 150px;
  z-index: 0;
}
<div class="post" data-name="post" draggable="true">1</div>
<div class="post" data-name="post" draggable="true">2</div>