2016-11-14 20 views
-1

我有兩個按鈕,只要點擊這些按鈕,我就可以更改我的樣式表。但是,一旦我刷新或者當我轉到我的網站上的下一頁時,樣式表就會恢復爲原始狀態,並且不會保留用戶如何設置它。我一直在尋找類似的例子,但只發現那些使用cookies,我想知道如何使用localStorage完成這項工作。 在此先感謝...使用localStorage保留樣式表

<script> 
    function swapStyleSheet(sheet) { 
    document.getElementById('pagestyle').setAttribute('href', sheet); 
    } 
</script> 

<div class="change"> 
    <h6>Change Stylesheet</h6> 
    <button onclick="swapStyleSheet('css/style2.css')">Dark</button> 
    <button onclick="swapStyleSheet('css/style.css')">Light</button> 
</div> 
+0

當然 - 您應該嘗試編寫該部分。 –

回答

0

是的。您可以使用以下內容:

localStorage.setItem('currentStyleSheet', 'css/style.css'); 
function swapStyleSheet(sheet) { 
    document.getElementById('pagestyle').setAttribute('href', sheet); 
    localStorage.setItem('currentStyleSheet', sheet); 
} 
window.onload = function() { 
    document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('currentStyleSheet')); 
} 
+0

感謝您的回覆。我已經用原來的腳本代替它,並且按鈕仍然有效,但是當我重新加載頁面時,樣式不被保留... – 100kasimpasali

相關問題