Javascript 在页面切换选项卡和重新加载选项卡时维护动态CSS
在我的应用程序中,用户可以通过单击按钮来更改页面的CSS。我希望,如果用户访问页面上的另一个链接或页面被重新加载,则所选样式应保持不变,即用户不必反复选择所选的样式/主题 我怎样才能做到这一点Javascript 在页面切换选项卡和重新加载选项卡时维护动态CSS,javascript,css,Javascript,Css,在我的应用程序中,用户可以通过单击按钮来更改页面的CSS。我希望,如果用户访问页面上的另一个链接或页面被重新加载,则所选样式应保持不变,即用户不必反复选择所选的样式/主题 我怎样才能做到这一点 功能开关\u样式(样式){ 如果(主题=“蓝色”){ document.getElementById(“test”).setAttribute('style','color:blue'); } else if(主题==“黑色”){ document.getElementById(“test”).setA
功能开关\u样式(样式){
如果(主题=“蓝色”){
document.getElementById(“test”).setAttribute('style','color:blue');
}
else if(主题==“黑色”){
document.getElementById(“test”).setAttribute('style','color:black');
}
}
黑色
示例文本
要存储值,您需要从浏览器添加本地存储。
详情如下:
您可以使用以下示例代码:
function switch_style (style)
{
if(theme == "blue"){
document.getElementById("test").setAttribute('style','color:blue');
}
else if(theme == "black"){
document.getElementById("test").setAttribute('style','color:black');
}
localStorage.setItem("style_theme", theme);
}
并对localstorage
var style_theme = localStorage.getItem("style_theme");
if(!style_theme){
style_theme = "blue" // set default theme which want to.
}
switch_style(style_theme);
基于此,您可以使用本地存储调用函数。:
//调整s开关样式以使用本地存储
function switch_style (theme) {
// making switch_style update local staorage any time page theme is changed
localStorage.setItem('currentThemeColor', theme);
if(theme == "blue"){
document.getElementById("test").setAttribute('style','color:blue');
} else if (theme == "black") {
document.getElementById("test").setAttribute('style','color:black');
}
}
// for every page add an eventLister that runs after the page load to get the currentThemeColor from localStorage and apply it ont the current page...
// Example:
window.addEventListener("DOMContentLoaded", function () {
// getting currentThemeColor from localStorage;
const currentThemeColor = localStorage.getItem('currentThemeColor') || "blue"; // setting blue as fallball color if localStorage has no currentThemeColor
// updating page theme
switch_style(currentThemeColor);
})
您可以使用javascript localstorage或cookies在客户端保存此属性,并从客户端加载(如果存在),否则将其设置为默认值。@AniketKariya是正确的。正如他所说,您必须使用localStorage
实现逻辑。添加了解决方案。请注意,您在onclick
属性上缺少了结束符(“
)。感谢您的回答!这也是正确的。向上投票。如果要阻止代码重复,请将setItem
移到外侧。@RillaThank您共享了解决方案!:)