Thuộc tính cssText

Thuộc tính cssText cho phép thiết lập CSS styles hàng loạt bằng một dòng. Khi đó toàn bộ nội dung của thuộc tính style sẽ được ghi đè.

Cú pháp

javascriptphần tử.style.cssText = 'thuộc tính 1: giá trị; thuộc tính 2: giá trị...'

Ví dụ

Hãy thiết lập một vài styles cho phần tử:

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

Ví dụ

Trong ví dụ này, phần tử ban đầu đã có styles trong thuộc tính style, nhưng thuộc tính cssText sẽ ghi đè nó:

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

Ví dụ

Để các styles trước đó không bị ghi đè, có thể làm như sau:

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

Xem thêm

  • phương thức getComputedStyle,
    lấy giá trị của thuộc tính CSS của phần tử