Javascript 如何动态加载外部 CSS 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2099517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:46:08  来源:igfitidea点击:

How to load in an external CSS file dynamically?

javascripthtmlcss

提问by Patel

I'm trying to create a dynamic page using external .css pages where the page color will get changed. Below is my code. But when I click the href, I am not getting any output. Can anyone please tell me what's the problem in my code?

我正在尝试使用外部 .css 页面创建一个动态页面,页面颜色将在其中更改。下面是我的代码。但是当我点击 时href,我没有得到任何输出。谁能告诉我我的代码有什么问题?

<script language="JavaScript">
function loadjscssfile(filename, filetype)
{
    if (filetype=="css")
    { 
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("mystyle.css", "css") 
</script>
<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a> 

I have modified my code as below. Still, I'm facing the problem of getting the output. No result. Can anyone please help me out?

我已经修改了我的代码如下。尽管如此,我仍然面临着获取输出的问题。没有结果。任何人都可以帮我吗?

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="css/newstyle.css" />
<script language="JavaScript" type="text/javascript">
function loadjscssfile(filename, filetype)
{
    if (filetype=="css") 
    {
        var fileref = document.createElement("link");
        fileref.rel = "stylesheet";
        fileref.type = "text/css";
        fileref.href = "filename";
        document.getElementsByTagName("head")[0].appendChild(fileref)
    }
}
loadjscssfile("oldstyle.css", "css") 
</script>
<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a> 
</head>

回答by Tim Goodman

Try this:

尝试这个:

var fileref = document.createElement("link");
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.href = "filename";
document.getElementsByTagName("head")[0].appendChild(fileref)

回答by vilhalmer

Tim Goodman's answer is correct, but instead of fileref.href = "filename";it should be fileref.href = filename;

蒂姆古德曼的答案是正确的,但不fileref.href = "filename";应该是fileref.href = filename;

Otherwise you're trying to load a file with the name "filename" rather than what you passed to the script.

否则,您将尝试加载名为“filename”的文件,而不是您传递给脚本的内容。

Alternately, if you're willing to use the jQuerylibrary, this can be accomplished in one line:
$("head").append("<link rel='stylesheet' id='extracss' href='"+filename+"' type='text/css' />");

或者,如果您愿意使用jQuery库,这可以在一行中完成:
$("head").append("<link rel='stylesheet' id='extracss' href='"+filename+"' type='text/css' />");

Also, about the first version of your script using setAttribute: Most browsers will only take setAttribute with an empty third parameter because of the way the spec is set up:
fileref.setAttribute("href", filename, "");

此外,关于使用 setAttribute 的脚本的第一个版本:由于规范的设置方式,大多数浏览器只会采用带有空的第三个参数的 setAttribute:
fileref.setAttribute("href", filename, "");

回答by user250418

Try adding a style line in your html and just using @import in the css to get the new file

尝试在你的 html 中添加一个样式行,然后在 css 中使用 @import 来获取新文件

回答by chirag

Use this code

使用此代码

document.getElementsByTagName("head")[0].appendChild('<link href="style.css" rel="stylesheet" type="text/css" />');

it might work, your code may working but due to some another css it won't reflected.

它可能会工作,您的代码可能会工作,但由于其他一些 CSS,它不会反映出来。

回答by T.Raghavendra

Change this

改变这个

<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a> 

to

<a href="javascript:void(0)" onclick="loadjscssfile('oldstyle.css','css');">Load "oldstyle.css"</a> 

I belive the onclick, event to href will reload the new file.

我相信 onclick,href 事件将重新加载新文件。

回答by Chetan Sastry

First of all, you can't have an anchor element in the <head>section. Secondly, are you sure your CSS path is correct? I'm asking because you already have a reference to css/newstyle.cssbut your are trying to load newstyle.css. Are you sure it's not css/newstyle.css?

首先,在<head>section中不能有anchor元素。其次,你确定你的 CSS 路径是正确的吗?我问是因为你已经有一个参考,css/newstyle.css但你正在尝试加载newstyle.css. 你确定不是css/newstyle.css

Edit:Hereis a working example of your own code. There is something else wrong. Try to statically link the CSS and see if you are getting the styles. If not, there may be errors in your stylesheet.

编辑:是您自己的代码的工作示例。还有其他问题。尝试静态链接 CSS,看看您是否获得了样式。如果没有,则样式表中可能存在错误。

By statically linking the stylesheet, I meant to say add this in your page instead of loading from javascript

通过静态链接样式表,我的意思是说在您的页面中添加它而不是从 javascript 加载

<link rel="stylesheet" type="text/css" href="css/oldstyle.css" />

回答by pib

That code should work, except perhaps you might want to add type="text/javascript" to your script tag.

该代码应该可以工作,除非您可能希望将 type="text/javascript" 添加到您的脚本标记中。

I tested the code via Firebug and it worked for me.

我通过 Firebug 测试了代码,它对我有用。

Maybe the problem is that your original stylesheet is still included in the page and thus overriding the style of your secondary stylesheet?

也许问题是您的原始样式表仍包含在页面中,从而覆盖了辅助样式表的样式?

回答by chirag

' document.createElement("link") ' creates hyper link object, not css style tag() element, so you are not able to apply this dynamically

' document.createElement("link") ' 创建超链接对象,而不是 css 样式的 tag() 元素,因此您无法动态应用它

correct me if i am wrong

如果我错了,请纠正我