gpt4 book ai didi

javascript - 新窗口中的外部样式表

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

目标:打开一个新窗口,插入元素,然后使用外部样式表将css样式应用于新窗口中的元素。

问题:我可以在新窗口中插入元素,让新窗口头部元素具有指向外部样式表的链接元素,但新窗口元素不受样式表的影响。

fiddle https://jsfiddle.net/1f2per3s/

Javascript

$('.button').on('click', function() {
let win = window.open();

let link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', '/stylesheets/my.css');
win.document.head.appendChild(link);

let div = document.createElement('div');
div.innerHTML = '<div> hello world</div>';
win.document.body.appendChild(div);
});

HTML

<div class="container">
<div class="button">
test element
</div>
</div>

最佳答案

如果您查看地址栏,该 URL 不在您的网站上(在 Chrome 中,它是 about:blank)。样式表的路径是相对的,找不到。

您可以使用完整的绝对 URL 来解决这个问题:

link.setAttribute('href', 'http://example.org/stylesheets/my.css');

https://jsfiddle.net/3xhrnpsa/ (使用 bootstrap 的 CSS 进行演示,使文本成为无衬线字体)

关于javascript - 新窗口中的外部样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366062/

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