简体   繁体   English

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

[英]How to load in an external CSS file dynamically?

I'm trying to create a dynamic page using external .css pages where the page color will get changed.我正在尝试使用将更改页面颜色的外部 .css 页面创建动态页面。 Below is my code.下面是我的代码。 But when I click the href , I am not getting any output.但是当我单击href时,我没有得到任何输出。 Can anyone please tell me what's the problem in my code?谁能告诉我我的代码有什么问题?

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

Try this:尝试这个:

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

Tim Goodman's answer is correct, but instead of fileref.href = "filename";蒂姆古德曼的回答是正确的,但不是fileref.href = "filename"; it should be 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.否则,您将尝试加载名称为“文件名”的文件,而不是您传递给脚本的文件。

Alternately, if you're willing to use the jQuery library, this can be accomplished in one line:或者,如果您愿意使用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:此外,关于使用 setAttribute 的脚本的第一个版本:由于规范的设置方式,大多数浏览器只会使用带有空的第三个参数的 setAttribute:
fileref.setAttribute("href", filename, "");

尝试在您的 html 中添加样式行,并在 css 中使用 @import 来获取新文件

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?也许问题是您的原始样式表仍然包含在页面中,从而覆盖了辅助样式表的样式?

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,它不会反映。

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 事件将重新加载新文件。

First of all, you can't have an anchor element in the <head> section.首先,您不能在<head>部分中有锚元素。 Secondly, are you sure your CSS path is correct?其次,你确定你的 CSS 路径是正确的吗? I'm asking because you already have a reference to css/newstyle.css but your are trying to load newstyle.css .我问是因为您已经引用了css/newstyle.css但您正在尝试加载newstyle.css Are you sure it's not css/newstyle.css ?你确定它不是css/newstyle.css吗?

Edit: Here is 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.尝试静态链接 CSS 并查看是否获得样式。 If not, there may be errors in your stylesheet.如果没有,您的样式表中可能有错误。

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" />

I did not like the idea of adding additional links to the document, as it leads to a memory leak.我不喜欢向文档添加额外链接的想法,因为它会导致内存泄漏。

Instead, I tried something else.相反,我尝试了其他方法。

In the document's head:在文件的头部:

<head>
<link id="changeme" rel="stylesheet" type="text/css" href="css/oldstyle.css" />
<!-- moar stuff hear -->
</head>

In JavaScript:在 JavaScript 中:

<script language="JavaScript">
function loadFile(filename) {
  const link = document.querySelector("#changeme");
  link.href = filename;
}
const sheets = ["/css/theme1.css", "/css/theme2.css", "/css/theme3.css"];
let pos = 0;
let timer = setInterval(()=>{
  loadFile(sheets[pos]);
  pos = pos + 1;
  if (pos >= sheets.length) {
    pos = 0;
  }
}, 2000);
</script>

This simply replaces the href already in your head, easily identified using a handy id.这只是替换了您脑海中已经存在的 href,使用方便的 id 可以轻松识别。 In this sample, every two seconds it moves from theme1 to theme2, to theme3, back to theme1 again, until someone leaves the page.在这个示例中,它每两秒从主题 1 移动到主题 2,再到主题 3,再回到主题 1,直到有人离开页面。 Great for indecisive websites.非常适合优柔寡断的网站。

(I have no idea how portable this is, so caveat emptor... but it works on Firefox and Chromium, which was good enough for my needs). (我不知道它的便携性如何,所以请注意……但它适用于 Firefox 和 Chromium,这足以满足我的需求)。

' 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如果我错了,请纠正我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM