gpt4 book ai didi

javascript - 当访问者在页面之间移动时,如何使 toggleClass 更改持续存在?

转载 作者:行者123 更新时间:2023-11-30 13:59:44 25 4
gpt4 key购买 nike

撇开潜在的编码效率问题不谈,我为我的切换按钮组合了一个 jQuery 函数。单击打开和关闭开关时,网站会为暗模式应用各种 CSS 类和样式。这非常有效:

$(function() {
$(".slider.round").click(function() {
$("#canvas-wrapper").toggleClass("dark-canvas");
$("#page-body-wrapper p").toggleClass("dark-body-text");
$("h2, h3, .summary-title a, .summary-read-more-link, .summary-excerpt a, #block-yui_3_17_2_32_1456852631790_12688 a").toggleClass("dark-headings-links");
$("#block-yui_3_17_2_2_1457035305182_118918 h2").toggleClass("dark-intro");
$(".summary-item").toggleClass("dark-summary");
$(".summary-excerpt strong, #sidebar-one h2").toggleClass("dark-excerpt-sidebar");
$("#sidebar-one, .sqs-col-1").toggleClass("dark-sidebar");
$(".summary-metadata-item a, .summary-metadata-item--date").toggleClass("dark-metadata");
});
});

但是,有一个大问题。假设访问者打开黑暗模式,相应地改变外观。当他们重新加载页面或在页面之间移动时,此状态每次都会自行重置。当用户浏览一个深色界面时,这会很刺耳,然后突然呈现一个以白色为主的设计。

我可以向此函数添加什么以允许那些 toggleClass 状态在页面之间持续存在?另一位用户向我指出了 localStoragesessionStorage。不幸的是,我仍然是 jQuery 的新手,缺乏将复杂的东西组合在一起的知识——更不用说理解相关的术语了。

有人可以帮忙吗?这将是一个巨大的帮助和进步!

感谢百万人,你们是摇滚明星 :)

最佳答案

我建议您直接在 CSS 文件中简化代码。您完全没有必要使用 JavaScript 为每个元素添加大量类。

相反,您可以使用一个类,我们称它为“mode--dark”,我们将把它添加到正文中。

在您的 CSS 中,此类可以如下所示:

.mode--dark #canvas-wrapper {
// your styles
}

.mode--dark #page-body-wrapper p {
// your styles
}


//--------------------> right after body script start (this should go right after <body> tag
function getMode() {
// let's check whether key "mode" exists in our localStorage and if so return true, false otherwise
return localStorage.getItem('mode') == 'true' ? true : false;
}

var body = document.querySelector('body'),
modeClass = 'mode--dark',
switchClass = 'js-switch'; // add any class name to your input for switching between themes and retype it here


if (getMode()) {
body.classList.add(modeClass);
}

document.addEventListener('change', function (e) {
var target = e.target;

if (target.className.indexOf(switchClass) > -1) {
if(!getMode()) {
body.classList.add(modeClass);
// set dark mode to true
localStorage.setItem('mode', true);
} else {
body.classList.remove(modeClass);
// set dark mode to false
localStorage.setItem('mode', false);
}
}
});

//--------------------> right after body script end

//--------------------> this can be put anywhere start
document.addEventListener('DOMContentLoaded', function (e) {
var switchInput = document.querySelector('.' + switchClass);

if(getMode()) {
switchInput.checked = true;
}
});
//--------------------> this can be put anywhere end

关于javascript - 当访问者在页面之间移动时,如何使 toggleClass 更改持续存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56517457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com