javascript - 无需重新加载页面即可交换主题样式表的优雅方式

标签 javascript jquery css themes

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

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/

相关文章:

javascript - jquery - 没有相邻 "select"输入的目标标签

javascript - 加载时CSS淡入背景图像

css - 为什么第一节元素似乎包含在第 n 个子 sibling 计数中?

asp.net - 在窗口调整大小后根据图像宽度动态更改图像高度

javascript - CSS - 关闭 Canvas 问题

javascript - 首次对返回 Observable 的方法进行 Angular Testing

javascript - JQuery 复制文本并粘贴到文本区域

javascript - 引导表自定义搜索

javascript - 添加缩放会破坏菜单滚动功能

css - 用背景图片填充(达到一定高度)容器 div