HTML DOM 样式 zIndex 属性

htmlweb developmentfront end technology更新于 2025/6/11 5:32:17

HTML DOM 样式 zIndex 属性用于返回并修改 HTML 文档中定位元素的堆叠顺序。

语法

以下是语法 −

  • 返回 zIndex

object.style.zIndex
  • 修改 zIndex

object.style.zIndex = “value”

值

此处,值可以是 -

值说明
initial将此属性值设置为默认值。
inherit从其父元素继承此属性值。
auto元素根据其在 HTML 文档中的顺序堆叠。
number它表示一个整数,用于指定元素的堆叠顺序。

示例

让我们看一个 HTML DOM 样式 zIndex 属性的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      color: #000;
      height: 100vh;
   }
   .box1 {
      width: 100px;
      height: 100px;
      background: lightcoral;
      position: relative;
      top: 50px;
   }
   .box2 {
      width: 100px;
      height: 100px;
      background: lightgreen;
      position: relative;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem 0;
}
</style>
</head>
<body>
<h1>DOM Style zIndex Property Example</h1>
<div class='box1'></div>
<div class='box2'></div>
<button onclick="add()" class="btn">Change zIndex</button>
<script>
   function add() {
      document.querySelector('.box1').style.zIndex = "1";
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击“更改 zIndex”按钮可以更改红色和绿色框的顺序 −


相关文章


有用资源