我從網(wǎng)上下載了javascript代碼,它創(chuàng)建了一個按鈕來打開和關閉黑暗模式,它運行得非常好。在這里,我將只粘貼我到目前為止所寫的相關部分:
<script>
// Wait for document to load
document.addEventListener("DOMContentLoaded", function(event) {
//store in a variable whatever the data-theme is in the sessionStorage
var sessionVariable = sessionStorage.getItem("data-theme");
/*
// if it doesnt exist (which is null, i think) then it sets the data-theme value to light
if string(sessionVariable) == "null"{
document.documentElement.setAttribute("data-theme", "light");
// if it does exist, which means data-theme is either dark or light, then it sets it to that
} else{
document.documentElement.setAttribute("data-theme", string(sessionVariable))
}
*/
document.documentElement.setAttribute("data-theme", "light") //THIS IS THE LINE THAT WORKS, I WOULD LIKE TO REMOVE IT FOR THE COMMENTED OUT CODE ABOVE
// Get our button switcher
var themeSwitcher = document.getElementById("theme-switcher");
// When our button gets clicked
themeSwitcher.onclick = function() {
// Get the current selected theme, on the first run it should be `light`
var currentTheme = document.documentElement.getAttribute("data-theme");
// Switch between `dark` and `light`
var switchToTheme = currentTheme === "dark" ? "light" : "dark";
sessionStorage.setItem("data-theme", "currentTheme"); //store in the sessionStorage whatever the data-theme's value is (the currentTheme)
// Set our current theme to the new one
document.documentElement.setAttribute("data-theme", switchToTheme);
}
});
</script>
現(xiàn)在,我正在嘗試為它添加會話存儲功能。正如你在開始看到的,我注釋掉了一大塊代碼:我認為這應該可以,但事實并非如此,我從互聯(lián)網(wǎng)上抓取的原始未編輯行是我說過要替換的行。
所以,我的邏輯是,當頁面第一次打開時,顯然沒有& quot數(shù)據(jù)主題& quot存儲在會話存儲中。當?shù)诙衘avascript試圖獲取一個項目時數(shù)據(jù)主題& quot),它應該返回& quotnull & quot,對吧?。然后我設置它,如果data-theme為空(這意味著它還沒有被定義),它將主題設置為亮(默認模式),但是如果它確實被定義了,那么它將主題設置為亮或暗
然而,當我刪除我想刪除的那一行并取消注釋掉那段代碼時,按鈕就停止工作了。我想這是因為我的& quot如果& quot聲明。這是什么?sessionVariable不是& quotnull & quot當它還沒有被定義的時候。
下面一行
if string(sessionVariable) == "null"{
應改為
if (sessionVariable === "null"){
你的& quot如果& quot你是在和字符串null比較,而不是和實際的null比較 即
"null" /* this is string */
嘗試
if(sessionVariable === null)
這里null表示沒有任何值