บทนำ
JavaScript DOM มี property background ที่เป็น shorthand property ช่วยให้ตั้งค่าคุณสมบัติพื้นหลังหลายอย่างพร้อมกันในคำสั่งเดียว เช่น สี ภาพ ตำแหน่ง และการทำซ้ำ
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">คลิกเพื่อตั้งค่าพื้นหลัง</button>
<script>
function display() {
document.body.style.background = "url('https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg') repeat right top";
}
</script>
</body>
</html>
รูปแบบ Syntax
element.style.background = "color image repeat attachment position";
คำอธิบายแต่ละส่วน
| ส่วน | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| color | สีพื้นหลัง | #ffffff, red, rgb(255,0,0) |
| image | URL ภาพพื้นหลัง | url('image.jpg') |
| repeat | การทำซ้ำ | repeat, no-repeat, repeat-x, repeat-y |
| attachment | การเลื่อน | scroll, fixed, local |
| position | ตำแหน่ง | left top, center, right bottom |
ตัวอย่างเพิ่มเติม
// ตั้งค่าสี พร้อมภาพ ไม่ทำซ้ำ ตรงกลาง คงที่
element.style.background = "#f0f0f0 url('bg.png') no-repeat center center fixed";
// แค่สีอย่างเดียว
element.style.background = "linear-gradient(45deg, #ff0000, #0000ff)";
ข้อดีของ shorthand
โค้ดสั้น กำลังอ่านง่าย ประสิทธิภาพดีกว่าการตั้งค่าแต่ละ property แยกกัน