gpt4 book ai didi

javascript - 根据 URL 参数加载 CSS 文件

转载 作者:可可西里 更新时间:2023-11-01 13:33:59 24 4
gpt4 key购买 nike

你能帮我用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文件的头部?

最佳答案

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

}

等等

关于javascript - 根据 URL 参数加载 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21860409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com