gpt4 book ai didi

javascript - 使用 Javascript 将 css 链接插入页面的头部

转载 作者:行者123 更新时间:2023-11-30 12:45:13 25 4
gpt4 key购买 nike

包含此脚本的第 3 方网站:

 var foo = "Hello World!";

(function() {
var foo = "Goodbye World!";
document.write("<p class='something'>Inside our anomymous function foo means '" + foo + '".</p>');
})();

我现在想插入(使用纯 javascript)对样式表的外部引用。如何做到这一点?

使用 jquery 你可以这样做:

var css_link = $("<link>", { 
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');

但是我需要保留这个纯 javascript。

最佳答案

在 Chrome 中快速尝试下面,它有效..

var styleEl = document.createElement("link");
styleEl.type = "text/css";
styleEl.href = "style.css";
document.getElementsByTagName('head')[0].appendChild(styleEl);

关于javascript - 使用 Javascript 将 css 链接插入页面的头部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22748493/

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