交换主题样式表而不重新加载页面的优雅方式

时间:2017-05-08 23:15:36

标签: javascript jquery css themes

我正在寻找一种在页面加载时热插拔样式表的方法。这是我目前的解决方案,它有效,但它有一些限制/问题。

html head:

<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请求,因此更改不是即时的。另一个问题是,如果用户在使用页面时暂时断开连接,则会在没有主题的情况下离开。

1 个答案:

答案 0 :(得分:2)

使用备用样式表使其变得简单(两个主题的示例很简单)

<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);
    });
}
相关问题