我正在寻找一种在加载页面时热交换样式表的方法。这是我目前的解决方案,它有效但有一些限制/问题。
html 头:
<link id="theme" href="themes/theme1.css" rel="stylesheet" type="text/css">
js:
themes = [
"themes/theme1.css",
"themes/theme2.css"
];
function themeSwitch() {
var currentTheme = $("#theme").attr('href');
var themeID = themes.indexOf(currentTheme);
themeID = (themeID + 1) % themes.length;
$("#theme").attr('href', themes[themeID]);
}
我对这种方法的问题是,当函数被调用时,更改不是即时的,因为浏览器需要对 css 文件发出额外的 GET 请求。另一个问题是,如果用户在使用页面时暂时断开连接,他们将没有主题。
最佳答案
使用备用样式表使它变得简单(两个主题的示例是微不足道的)
<link id="theme" href="themes/theme1.css" rel="stylesheet" type="text/css">
<link id="alttheme" href="themes/theme2.css" rel="alternate stylesheet" type="text/css">
function themeSwitch() {
var t1 = document.getElementById('theme');
var t2 = document.getElementById('alttheme');
t1.disabled = !t1.disabled;
t2.disabled = !t1.disabled;
}
一种更通用的方式,允许任意数量的主题
<link class="theme" href="themes/theme1.css" rel="stylesheet" type="text/css">
<link class="theme" href="themes/theme2.css" rel="alternate stylesheet" type="text/css">
<link class="theme" href="themes/theme3.css" rel="alternate stylesheet" type="text/css">
var currentTheme = 0;
var themes = [].slice.call(document.querySelectorAll('link.theme'));
function themeSwitch() {
currentTheme = (currentTheme + 1) % themes.length;
themes.forEach(function(theme, index) {
theme.disabled = (index !== currentTheme);
});
}
最后,虽然您没有标记 jQuery,但您确实在代码中使用了 jQuery,因此,为了 jQuery 集:
<link class="theme" href="themes/theme1.css" rel="stylesheet" type="text/css">
<link class="theme" href="themes/theme2.css" rel="alternate stylesheet" type="text/css">
<link class="theme" href="themes/theme3.css" rel="alternate stylesheet" type="text/css">
var currentTheme = 0;
var themes = $('link.theme');
function themeSwitch() {
currentTheme = (currentTheme + 1) % themes.length;
themes.each(function(index, theme) {
theme.disabled = (index !== currentTheme);
});
}
关于javascript - 无需重新加载页面即可交换主题样式表的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43858633/