2017-05-08 94 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 –

相關問題