คุณสมบัติ cssText

คุณสมบัติ cssText ช่วยให้สามารถกำหนด CSS สไตล์แบบจำนวนมากในหนึ่งบรรทัดได้ โดย เนื้อหาทั้งหมดของแอตทริบิวต์ style จะถูกเขียนทับ

ไวยากรณ์

javascriptelement.style.cssText = 'property 1: value; property 2: value...'

ตัวอย่าง

ลองกำหนดสไตล์หลายรายการให้กับองค์ประกอบ:

html<p id="elem"></p>
javascriptlet elem = document.querySelector('#elem');
elem.style.cssText = 'color: red; font-size: 40px;';

ตัวอย่าง

ในตัวอย่างนี้ องค์ประกอบจะมีสไตล์อยู่แล้วในแอตทริบิวต์ style ตั้งแต่ต้น แต่คุณสมบัติ cssText จะเขียนทับมัน:

html<p id="elem" style="background: red;"></p>
javascriptlet elem = document.querySelector('#elem');
elem.style.cssText = 'color: red; font-size: 20px;';

ตัวอย่าง

เพื่อไม่ให้สไตล์เดิมถูกเขียนทับ สามารถทำได้ดังนี้:

html<p id="elem" style="background: green;"></p>
javascriptlet elem = document.querySelector('#elem');
elem.style.cssText += 'color: red; font-size: 20px;';

ดูเพิ่มเติม

  • เมธอด getComputedStyle,
    ซึ่งรับค่าคุณสมบัติ CSS ขององค์ประกอบ