我正在尝试使用 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]);
}
但是这会导致:
<style .skiptranslate {display: none};></style>
使用 javascript 在 DOM 中插入带有必要 CSS 的样式标签的正确方法是什么?
谢谢
最佳答案
顾名思义(and documentation says)Element.setAttribute
:
Adds a new attribute or changes the value of an existing attribute on the specified element.
这正是 <style>
上发生的情况元素。要解决此问题,请使用 .textContent
/ .innerText
或a text element而不是.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]);
}
关于css - Javascript 在头部添加样式标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14427400/