Javascript将CSS插入头部
使用下面的脚本,我在运行时包含文本并将css插入我的页面头部。但是,尽管插入了css,但它不会生效。为什么?Javascript将CSS插入头部,javascript,Javascript,使用下面的脚本,我在运行时包含文本并将css插入我的页面头部。但是,尽管插入了css,但它不会生效。为什么? (function () { var styleEl = document.createElement("link"); styleEl.type = "text/css"; styleEl.href = "/static/css/widgets.css"; //document.getElementsByTagName('head')[0].appen
(function () {
var styleEl = document.createElement("link");
styleEl.type = "text/css";
styleEl.href = "/static/css/widgets.css";
//document.getElementsByTagName('head')[0].appendChild(styleEl);
document.head.appendChild(styleEl);
var foo = "Goodbye World!";
document.write("<p class='example-widget-container'>Inside our anomymous function foo means '" + foo + '".</p>');
})();
(函数(){
var styleEl=document.createElement(“链接”);
styleEl.type=“text/css”;
styleEl.href=“/static/css/widgets.css”;
//document.getElementsByTagName('head')[0].appendChild(styleEl);
document.head.appendChild(styleEl);
var foo=“再见,世界!”;
在我们的匿名函数foo中写入(“
”);
})();
您忘记添加rel=“stylesheet”
,这对于声明样式表
标记很重要
以下是设置了rel
属性的更新代码:
(function () {
var styleEl = document.createElement("link");
styleEl.type = "text/css";
styleEl.href = "/static/css/widgets.css";
style.rel = "stylesheet";
//document.getElementsByTagName('head')[0].appendChild(styleEl);
document.head.appendChild(styleEl);
var foo = "Goodbye World!";
document.write("<p class='example-widget-container'>Inside our anomymous function foo means '" + foo + '".</p>');
})();
(函数(){
var styleEl=document.createElement(“链接”);
styleEl.type=“text/css”;
styleEl.href=“/static/css/widgets.css”;
style.rel=“样式表”;
//document.getElementsByTagName('head')[0].appendChild(styleEl);
document.head.appendChild(styleEl);
var foo=“再见,世界!”;
在我们的匿名函数foo中写入(“
”);
})();
只是猜测,但尝试添加rel=“stylesheet”?不要使用文档。编写!请参阅中的警告。改用DOM方法。@Adrian Mitev成功了,谢谢!您想添加一个答案吗。