บทนำ
เมื่อต้องการให้ภาพพื้นหลังไม่เลื่อนตามเนื้อหาเมื่อผู้ใช้ scroll หน้าเว็บ สามารถใช้ property backgroundAttachment ของ JavaScript DOM ได้ property นี้ควบคุมพฤติกรรมของ background image ว่าจะคงที่หรือเลื่อนตามเนื้อหา
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">คลิกเพื่อตั้งค่าพื้นหลัง</button>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<p>Demo Text</p>
<script>
function display() {
document.body.style.background = "url('https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg') no-repeat right top";
document.body.style.backgroundAttachment = "fixed";
}
</script>
</body>
</html>
คำอธิบาย
- backgroundAttachment = "fixed" - ทำให้ภาพพื้นหลังคงที่บน viewport ไม่เลื่อนเมื่อ scroll
- backgroundAttachment = "scroll" - ค่าเริ่มต้น ภาพเลื่อนตามเนื้อหา
- backgroundAttachment = "local" - ภาพเลื่อนตาม element container
การใช้งานร่วมกับ background shorthand
สามารถตั้งค่าทั้งหมดในบรรทัดเดียวได้:
element.style.background = "url('image.jpg') no-repeat center center fixed";