Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีตั้งค่าคุณสมบัติพื้นหลังทั้งหมดในบรรทัดเดียวด้วย JavaScript DOM

บทนำ

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)
imageURL ภาพพื้นหลัง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 แยกกัน