當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM Style zIndex屬性用法及代碼示例

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>

輸出

這將產生以下輸出 -

點擊 ”Change zIndex” 按鈕更改紅色和綠色框的順序 -

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM Style zIndex Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。