我正在尝试使用 javascript 将一些 css 添加到内部样式表中。这是我使用过的代码:
function googleJS(){
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('style');
newScript.setAttribute('.skiptranslate { display: none; }');
var bodyClass = doc.getElementsByTagName('head')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[2]);
}
Run Code Online (Sandbox Code Playgroud)
然而这会导致:
<style .skiptranslate {display: none};></style>
Run Code Online (Sandbox Code Playgroud)
使用 javascript 在 DOM 中插入带有必要 CSS 的样式标签的正确方法是什么?
谢谢
顾名思义(和文档所说)Element.setAttribute:
添加新属性或更改指定元素上现有属性的值。
这正是<style>元素上发生的情况。要解决此问题,请使用.textContent/.innerText或文本元素而不是.setAttribute()。
function googleJS(){
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('style');
var content = doc.createTextNode('.skiptranslate { display: none; }');
newScript.appendChild(content);
var bodyClass = doc.getElementsByTagName('head')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[2]);
}
Run Code Online (Sandbox Code Playgroud)