gpt4 book ai didi

javascript - 在 JavaScript 中分配样式表会创建良好的 html,但不会显示样式

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:04 24 4
gpt4 key购买 nike

我有一些 Javascript 打开一个空白窗口,为它分配一个样式表,然后向它写入一些文本。这一切都很好,除了内容没有应用样式。

代码如下所示:

var newWindow = window.open('', 'SecondWindow', 'toolbar=0,stat=0');
var style = newWindow.document.createElement('link');
style.type = "text/css";
style.rel = "stylesheet";
style.href = "styles/style.css";
newWindow.document.getElementsByTagName("head")[0].appendChild(style);
newWindow.document.body.innerHTML="<p class='verystylish'>Hello world!</p>";

如果我使用 Firefox Web Developer 工具查看生成的源代码,将其保存为 html 文件,然后手动打开 html 文件,它会正确应用样式,所以看起来我需要做一些事情来强制浏览器以某种方式应用样式或重新呈现页面。有什么建议吗?

编辑添加,生成的源代码如下:

<html>
<head>
<title></title>
<link href="styles/style.css" rel="stylesheet" type="text/css">
<head>
<body>
<p class='verystylish'>Hello world!</p>
</body>
</html>

问题是没有为该段落分配任何样式。但是打开具有相同源代码的文件可以正确呈现。

最佳答案

默认打开一个新窗口,URL 为“about:blank”。由于这个原因,相对 URL 引用将不起作用。要更改窗口的位置以匹配原始文档,请调用:

newWindow.document.open();

然后您应该将您想要的文档的框架写入窗口。如果需要,您现在可以包含样式表,因为 document.write 是一种比 DOM 方法更可靠的跨旧浏览器添加样式表的方法。此方法还允许您编写 DOCTYPE,这样您就不会意外地进入 Quirks 模式。

newWindow.document.write(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'+
'<html><head>'+
' <link rel="stylesheet" href="styles/style.css">'+
'</head><body>'+
'</body></html>'+
);
newWindow.document.close();

关于javascript - 在 JavaScript 中分配样式表会创建良好的 html,但不会显示样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/654114/

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