คุณสมบัติ zIndex สไตล์ HTML DOM ส่งคืนและแก้ไขลำดับการเรียงซ้อนขององค์ประกอบที่วางตำแหน่งในเอกสาร HTML
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
-
ส่งคืน zIndex
object.style.zIndex
-
กำลังแก้ไข zIndex
object.style.zIndex = “value”
คุณค่า
ในที่นี้ ค่าสามารถเป็น −
| ค่า | คำอธิบาย |
|---|---|
| เริ่มต้น | ตั้งค่าคุณสมบัตินี้เป็นค่าเริ่มต้น |
| สืบทอด | รับค่าคุณสมบัตินี้จากองค์ประกอบหลัก |
| อัตโนมัติ | ในนั้นองค์ประกอบจะเรียงกันตามลำดับในเอกสาร HTML |
| หมายเลข | แสดงจำนวนเต็มที่ระบุลำดับสแต็กขององค์ประกอบ |
ตัวอย่าง
ให้เราดูตัวอย่างคุณสมบัติ 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 ” เพื่อเปลี่ยนลำดับของกล่องสีแดงและสีเขียว -
