我有一個 javascript 應用程式,由于一些晦澀的原因,我需要:
- 將樣式注入我的 html 頭部
- 稍后從我的 html 頭中洗掉這些樣式
我現在的簡化設定是這樣的......
注入<style ...>標簽:
const css = `
* {
outline: 2px dashed lime;
}
`;
const styleEl = document.createElement('style');
styleEl.id = 'myid';
document.head.appendChild(styleEl);
styleEl.appendChild(document.createTextNode(css));
還有一次我想再次洗掉這些樣式,使用我分配的標識來標識<style ...>標簽,因為很多其他樣式節點都在頭部:
const styleElement = document.getElementById('myid');
if (styleElement && styleElement.parentNode) styleElement.parentNode.removeChild(styleElement);
我認為標簽id上<style ...>的不是有效的 HTML。但也想不出另一種優雅的方式來解決這個問題。在這種情況下,我不能使用行內樣式,因為樣式應該應用整個檔案(實際上是針對注入的 iframe)。
非常感謝您的想法和幫助!
uj5u.com熱心網友回復:
您不必再次通過 id 獲取它。你有它在styleEl變數中,所以只需將它從 DOM 中洗掉,如下所示:
styleEl.remove(); // remove it from the DOM
您可以反復執行此操作。追加和洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426150.html
標籤:javascript html css dom
