簡體   English   中英

你可以在不添加樣式屬性的情況下使用 JavaScript 為元素設置樣式嗎?

[英]Can you style an element with JavaScript without adding a style attribute?

當您在 JavaScript 中編寫element.style = "..."時,將style屬性添加到您添加樣式的元素。 有沒有辦法在沒有style屬性、沒有任何庫的情況下添加樣式?

如果你能想出一個以元素為目標的選擇器,另一個選擇是附加一個包含該選擇器的樣式表:

 const styleTag = document.head.appendChild(document.createElement('style')); styleTag.textContent = 'div { color: blue; }';
 <div>Some div</div>

如果允許您以某種方式更改元素,例如添加類或其他屬性,則會更可靠:

 const div = document.querySelector('div'); const className = `_${('' + Math.random()).slice(2)}`; div.classList.add(className); const styleTag = document.head.appendChild(document.createElement('style')); styleTag.textContent = `.${className} { color: blue; }`;
 <div>Some div</div>

  • styles標簽內添加一個 CSS 類
  • 使用DOMContentLoaded事件在加載文檔時向元素添加類
  • 通過標簽名獲取elment
  • 使用 vanillaJS 中的setAttribute方法將 CSS 類添加到您的標簽元素
  • 通過這種方式,它可能更易於維護 yoru 代碼,因為您在 css 級別進行更改,並且 JS 自動將聲明的 css 類中的值tanken

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Example</title> <style> .styles { color: red; } </style> </head> <body> <p>Hello there</p> <script> let paragraph = document.querySelector("p") document.addEventListener("DOMContentLoaded", () => { paragraph.setAttribute("class", "styles") }) </script> </body> </html>

使用 JS,您可以向 DOM 寫入任何內容,包括<style>標簽。 例如:

 const el = document.getElementById('changeColor'); el.onclick = function(e) { const s = document.createElement('style'); s.innerHTML = '.box { background-color: yellow; }'; document.querySelector('body').appendChild(s); }
 .box { width: 150px; height: 150px; background-color: red; color: white; padding: 20px; } #changeColor { margin: 10px 0; }
 <body> <button type="button" id="changeColor">Change It</button> <div class="box">This is a box</div> </body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM