Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript将CSS插入头部_Javascript - Fatal编程技术网

Javascript将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

使用下面的脚本,我在运行时包含文本并将css插入我的页面头部。但是,尽管插入了css,但它不会生效。为什么?

(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中写入(“

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中写入(“

foo表示“+foo+””

”); })();
只是猜测,但尝试添加rel=“stylesheet”?不要使用
文档。编写
!请参阅中的警告。改用DOM方法。@Adrian Mitev成功了,谢谢!您想添加一个答案吗。