gpt4 book ai didi

javascript - 使用 appendChild 将 CSS 附加到文档无法按预期工作

转载 作者:行者123 更新时间:2023-11-28 08:49:32 24 4
gpt4 key购买 nike

我正在尝试使用以下代码将 font-face 的 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('style');
style.type = 'text/css';
style.appendChild(this.externalWindow.document.createTextNode(css));
head.appendChild(style);

当我这样做时,它似乎没有将 CSS 识别为 CSS,甚至在源代码中它也没有突出显示为 CSS。

broken css image

但是当我这样做并使用 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>');

working css image

最佳答案

您可以:

  1. 添加一个空的 <style>元素到 externalWindow.document
  2. 然后捕获 stylesheet来自<style>的对象元素
  3. 然后填充 stylesheet具有样式规则的对象,使用 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);

关于javascript - 使用 appendChild 将 CSS 附加到文档无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58940309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com