单击时切换 z-index 更改 (vanillaJS)

switch z-index change on click (vanillaJS)

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

<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>