2017-05-08 26 views
0

我正在寻找一种方式来加载页面时热插拔样式表。这是我目前的解决方案,它的工作原理,但它有一些限制/问题。优雅的方式交换主题样式表,无需重新加载页面

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

的浏览器需要进行额外的GET请求我的这种方法的问题是,当函数被调用的变化不是瞬间为css文件。另一个问题是,如果用户在使用该页面时暂时断开连接,他们将被留下而没有主题。

+0

可能的重复[如何使用jQuery切换我的CSS样式表?](http://stackoverflow.com/questions/7846980/how-do-i-switch-my-css-stylesheet-using-jquery) – Qhuea

+0

@Qhuea该问题的解决方案每次切换主题时都需要GET请求。 – luctowers

回答

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); 
    }); 
} 
+0

太棒了,谢谢!我把它标记为Jquery。 – luctowers

+0

我没有看到jQuery标签,对不起:p –

相关问题