动态加载外部CSS文件 [英] Dynamically loading an external CSS file

查看:97
本文介绍了动态加载外部CSS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用外部.css页面创建动态页面,其中页面颜色将更改。下面是我的代码。但是当我点击 href ,我没有得到任何输出。任何人都可以告诉我的代码中的问题是什么?任何建议或想法。

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 what's the problem in my code? Any suggestions or ideas please.

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


推荐答案

Tim Goodman的回答是正确的, c $ c> fileref.href =filename; 应为 fileref.href = filename;

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

否则,你试图加载一个名为filename而不是你传递给脚本的文件。

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

愿意使用 jQuery 库,可以在一行中完成:

$(head)。append(< link rel ='stylesheet'id ='extracss'href ='+ filename +'type ='text / css'/>);

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

此外,关于使用setAttribute的脚本的第一个版本:大多数浏览器只会使用setAttribute和一个空的第三个参数, up:

fileref.setAttribute(href,filename,);

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, "");

这篇关于动态加载外部CSS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆