2016-02-23 96 views
0

我有一個簡單的樣式表切換器,它可以在兩個樣式表之間切換。 當我點擊紅色時,它會從灰色切換爲紅色,當我嘗試從紅色切換回灰色時,它會回覆開啓。樣式表切換緩存/不改回原始樣式表

我添加了時間戳以防止緩存。 我的代碼如下

<link rel="stylesheet" title="grey" href="css/grey.css" type="text/css"> 

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script> 
<script language="javascript"> 
$(document).ready(function() { 
var timestamp =+Date.now(); 
console.log(timestamp); 
$('#red').click(function(){ 
    $('link[href="css/grey.css"]').attr('href','css/red.css?='+Date.now()); 

}); 
$('#grayscale').click(function(){ 
    $('link[href="css/red.css"]').attr('href','css/grey.css?='+Date.now()); 
    //alert("grey"); 
}); 

}); 

</script> 
</head> 

<body> 
<p> lorem ipsum lorem iuipsum </p> 



<button id="original">Original</button><br /> 
<button id="grayscale">Grayscale</button> 


<a href="#" id="red"> red</a> 
<a href="#" id="grayscale"> grey</a> 

回答

0

我重寫和替代的解決方案,whihc與時間戳工作。

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title> Theme Switcher </title> 

<!--<link rel="stylesheet" title="red" href="css/red.css" type="text/css"> 
    <link rel="stylesheet" title="grey" href="css/grey.css" type="text/css">--> 

    <link href="css/grey.css" rel="stylesheet" type="text/css" id="theme"> 


<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script> 
<script language="javascript"> 

$(document).ready(function() { 
var timestamp =+Date.now(); 
console.log(timestamp); 

$("button[data-theme]").click(function() { 
    //alert($(this).data("theme")); 
    $("head link#theme").attr("href", $(this).data("theme")); 
}); 


}); 




</script> 
</head> 

<body> 
<p> lorem ipsum lorem iuipsum </p> 




<button id="grayscale" data-theme="css/grey.css">Gray Theme</button> 
<button id="redscale" data-theme="css/red.css"> Red Theme</button> 





</body> 
</html>