Javascript 使用appendChild将CSS追加到文档中不会';I don’我没有按预期工作
我正在尝试使用以下代码手动将字体的CSS添加到新窗口:Javascript 使用appendChild将CSS追加到文档中不会';I don’我没有按预期工作,javascript,html,css,Javascript,Html,Css,我正在尝试使用以下代码手动将字体的CSS添加到新窗口: const css = '@font-face {font-family:Roboto; src:url("assets/fonts/Roboto-Black.ttf");}'; const head = this.externalWindow.document.getElementsByTagName('head')[0]; const style = this.externalWindow.document.createElement(
const css = '@font-face {font-family:Roboto; src:url("assets/fonts/Roboto-Black.ttf");}';
const head = this.externalWindow.document.getElementsByTagName('head')[0];
const style = this.externalWindow.document.createElement('style');
style.type = 'text/css';
style.appendChild(this.externalWindow.document.createTextNode(css));
head.appendChild(style);
当我这样做的时候,它似乎没有将CSS识别为CSS,甚至在源代码中,它也没有突出显示为CSS
但是当我这样做并使用document.write编写样式时,它可以很好地工作并将字体作为字体加载
this.externalWindow.document.write('<html><head><style>' + '@font-face {font-family:Roboto ;src:url("assets/fonts/Roboto-Black.ttf");}' + '.inner{font-family: Roboto;font-size: 40pt;text-align: justify;}' + '</style></head><body onload="window.print();window.close()"><p class="head">' + this.headContents + '</p> <p class="inner">' + this.innerContents + '</p> <p class="sign">' + this.signContents + '</p></body></html>');
this.externalWindow.document.write(''+'@font-face{font-family:Roboto;src:url(“assets/font/Roboto Black.ttf”);}'+'.inner{font-family:Roboto;font-size:40pt;text-align:justify;}'+''+this.headContents+'
'+this.innerContents+
'+this.signContents+);
.createTextNode
假定您的输入是文本,而不是代码,并将其转义为文本()
相反,请尝试使用style.innerHTML=css
您可以:
将空的
元素添加到externalWindow.document
然后从该
元素中获取样式表
对象
然后使用insertRule
示例:
// Append <style> element to <head> of externalWindow.document
const head = this.externalWindow.document.head;
const style = this.externalWindow.document.createElement('style');
head.appendChild(style);
// Grab external stylesheet object
const externalStylesheet = style.sheet;
// Insert style rules into external stylesheet
externalStylesheet.insertRule('@font-face {font-family: Roboto; src: url("assets/fonts/Roboto-Black.ttf");}', 0);
externalStylesheet.insertRule('.inner {font-family: Roboto; font-size: 40pt; text-align: justify;}', 1);
//将元素追加到externalWindow.document的
const head=this.externalWindow.document.head;
const style=this.externalWindow.document.createElement('style');
头。附属物(样式);
//抓取外部样式表对象
const externalStylesheet=style.sheet;
//将样式规则插入外部样式表
insertRule('@font-face{font-family:Roboto;src:url(“assets/fonts/Roboto-Black.ttf”);}',0);
insertRule('.inner{font-family:Roboto;字体大小:40pt;文本对齐:justify;}',1);
Google提供使用.innerHTML
作为使用.createTextNode()
的替代方法。还有一种方法允许您直接在DOM中操作样式表。我该如何使用它?”.createTextNode
假定您的输入是文本,而不是代码,并将其转义为“文本”:此信息来自何处?链接站点没有提到这一点。而且,如果你用预先生成的
检查一个网站,你会看到他们的.childNodes
是文本
对象……遗憾的是,这没有按预期工作。
为空。我还必须将上述内容修改为constexternalstylesheet=style.sheet作为CSSStyleSheet在JSFIDLE上,我只能让它与font
和类一起工作。试图将font-family
应用于整个文档对我无效: