簡體   English   中英

瀏覽網站時如何維護選定的 CSS 表?

[英]How to maintain the selected CSS sheet when navigating through website?

我目前正在建立我的第一個網站。 我設法插入了兩個按鈕,允許用戶在兩個 CSS 工作表(淺色主題和深色主題,淺色主題是默認主題)之間進行切換。 但是現在我面臨一個我不知道如何解決的問題:當我打開我的網站並將主題更改為深色主題時,如果我單擊菜單中的另一個頁面(我有多個 HTML 頁面)主題回到默認值。 我希望能夠允許用戶在瀏覽整個網站時保持相同的 CSS 表。 我知道我必須使用 localStorage 才能這樣做,但是每當我嘗試在網上找到一些代碼時,我都無法使其工作。 我將在此處插入迄今為止在我的網站中擁有的 HTML 和 JS 代碼。 請注意,我對 web 編程非常陌生。

非常感謝所有幫助我的人:)

HTML頭段:

<link id="pagestyle" rel="stylesheet" type="text/css" href="stylesheetlight.css">

HTML 機身部分:

<div class="themebuttons">
        <button onclick="swapStyleSheet('stylesheetlight.css')"><img src="sun.svg"></button>
        <button onclick="swapStyleSheet('stylesheetdark.css')"><img src="moon.svg"></button>
</div>

JAVASCRIPT代碼

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

如果沒有您的所有相關代碼,這更像是一個建議而不是一個有保證的解決方案,但是使用localStorage您可以更改您的swapStyleSheet function 以在每次更新時保存當前樣式表。

唯一需要的其他更改是類似於事件偵聽器,它在頁面加載時從localStorage中提取保存的樣式表值並將其發送到您的swapStyleSheet function。

function swapStyleSheet(sheet) {
  document.getElementById('pagestyle').setAttribute('href', sheet);
  if(localStorage) localStorage.setItem("stylesheet", sheet);
}
window.addEventListener("load", e => {
  if(localStorage && localStorage.getItem("stylesheet")) swapStyleSheet(localStorage.getItem("stylesheet"));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM