使用 JavaScript 動(dòng)態(tài)注入 CSS
動(dòng)態(tài)操作網(wǎng)頁(yè)的樣式可以極大地增強(qiáng)用戶(hù)體驗(yàn)。 JavaScript 通過(guò)動(dòng)態(tài)添加或修改 CSS 規(guī)則提供了實(shí)現(xiàn)此目的的強(qiáng)大方法。讓我們探索如何使用 JavaScript 將 CSS 規(guī)則合并到網(wǎng)頁(yè)中。
創(chuàng)建新樣式節(jié)點(diǎn)并將其添加到文檔中是一種簡(jiǎn)單的方法。 JavaScript 允許您以編程方式將 CSS 規(guī)則定義為文本,然后附加新的
例如,考慮以下 JavaScript 代碼:
<code class="javascript">// Define your CSS rules as text var styles = ` .qwebirc-qui .ircwindow div { font-family: Georgia,Cambria,"Times New Roman",Times,serif; margin: 26px auto 0 auto; max-width: 650px; } .qwebirc-qui .lines { font-size: 18px; line-height: 1.58; letter-spacing: -.004em; } .qwebirc-qui .nicklist a { margin: 6px; } `; // Create a new style node for the CSS rules var styleSheet = document.createElement("style"); styleSheet.textContent = styles; // Append the style node to the document head document.head.appendChild(styleSheet);</code>
此代碼片段在 styles 變量中定義 CSS 規(guī)則。隨后,它創(chuàng)建了一種新的