你能帮我用javascript加载基于URL参数的CSS文件吗?
我有3个参数(一个,两个和三个),我有3个CSS文件。
if (window.location.search.search(/[?&]parameter=one(?:$|&)/) !== -1)
{
What code should go in there to load the css?
}
JS应该保存在HTML文件的标题中吗?
答案 0 :(得分:2)
if (window.location.search.search(/[?&]parameter=one(?:$|&)/) !== -1) {
var $ = document; // shortcut
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!$.getElementById(cssId))
{
var head = $.getElementsByTagName('head')[0];
var link = $.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css/one.css';
link.media = 'all';
head.appendChild(link);
}
}
else if(window.location.search.search(/[?&]parameter=two(?:$|&)/) !== -1)
{
//Another way & More simple
var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "css/two.css";
document.getElementsByTagName("head")[0].appendChild(ss);
}
等等