คุณสมบัติ top ของ HTML DOM Style ใช้สำหรับคืนค่าและแก้ไขตำแหน่งด้านบนขององค์ประกอบ HTML ที่มีการจัดตำแหน่ง (positioned) ในเอกสาร HTML
ไวยากรณ์
1. การคืนค่า top
object.top
2. การแก้ไข top
object.top = "value"
ที่นี่ value สามารถเป็นได้ดังนี้:
| ลำดับ | ค่า & คำอธิบาย |
|---|---|
| 1 | initial ตั้งค่าคุณสมบัตินี้เป็นค่าเริ่มต้น |
| 2 | inherit สืบทอดค่าคุณสมบัติจากองค์ประกอบพาเรนต์ |
| 3 | percentage(%) กำหนดค่าเป็นเปอร์เซ็นต์ของความกว้างขององค์ประกอบพาเรนต์ |
| 4 | length กำหนดค่า top ในหน่วยความยาว |
| 5 | auto ให้เบราว์เซอร์ตั้งค่าตำแหน่ง top เอง |
ตัวอย่าง
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 40%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem 0;
}
.square {
width: 100px;
height: 100px;
background: #db133a6b;
position: relative;
}
.show {
font-size: 1.2rem;
margin: 1rem 0;
}
</style>
<body>
<h1>ตัวอย่างคุณสมบัติ Style top ของ DOM</h1>
<div class='square'></div>
<button onclick="set()" class="btn">ตั้งค่าตำแหน่งด้านบน</button>
<script>
function set() {
document.querySelector('.square').style.top = "200px";
}
</script>
</body>
</html>
ผลลัพธ์
คลิกปุ่ม "ตั้งค่าตำแหน่งด้านบน" เพื่อตั้งค่าตำแหน่งด้านบนของสี่เหลี่ยมสีชมพู