css 使用javascript进行z-index分层

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了css 使用javascript进行z-index分层相关的知识,希望对你有一定的参考价值。

function layering() {
    var count = 0;
    var arr = [];
    var layer1, later2, layer3 = 0;
    for (var i = 1; i <= 3; i++) {
        var temp = ".layer-" + i;
        arr.push(document.querySelector(temp));
    }


    for (var m = 0; m <= 2; m++) {
        arr[m].addEventListener("click", function () {
            count += 1
            this.style.zIndex = count;
            console.log("you clicked on " + this.className);
        });
    }

}

layering();
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>positioning div's</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <div class="content">
      <div class="layer-1">layer-1</div>
      <div class="layer-2">layer-2</div>
      <div class="layer-3">layer-3</div>
      <br>
    </div>
    <p>Click on the square to change its ordering and bring it to the top</p>
    
    <script src="index.js"></script>
  </body>
</html>
.layer-1 {
  height: 100px;
  width: 100px;
  
  background-color: red;
  
  position: absolute;
  top: 0;
  left: 0;
}

.layer-2 {
  height: 100px;
  width: 100px;
  
  background-color: yellow;
  
  position: absolute;
  top: 30px;
  left: 30px;
}

.layer-3 {
  height: 100px;
  width: 100px;
  
  background-color: green;
  
  position: absolute;
  top: 60px;
  left: 60px;
}

.content {
  position: relative;
  height: 160px;
  width: 160px;
}

以上是关于css 使用javascript进行z-index分层的主要内容,如果未能解决你的问题,请参考以下文章

CSS样式中z-index属性

理解z-index

css菜鸟:为啥当Position为absolute时,z-index就无效了呢?

CSS剩余属性;JavaScript数据类型

css Z-index.css

CSS的“层”峦“叠”翠