提问者:小点点

在页面和重新加载时的切换选项卡上维护动态CSS


在我的应用程序中,有一个选项让用户在单击按钮时更改页面的CSS。 我想,如果用户访问页面上的另一个链接或如果页面被重新加载,所选的风格应该保持,即用户不应该不得不选择一次又一次选择的风格/主题。

我怎样才能做到这一点呢?

null

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');
    }
    
    }
     
<button type="button" class="btn btn-dark" onclick="switch_style('blue') id="blue">Blue</button>
     <button type="button" class="btn btn-dark" onclick="switch_style('black')id="black">Black</button>
     <p id="test">SAMPLE TEXT</p>


     

null


共2个答案

匿名用户

为了存储值,您需要从浏览器添加localstorage。 以下是它的详细信息:https://www.w3schools.com/jsref/prop_win_localstorage.asp

可以使用以下示例代码:

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);

基于此,您可以调用函数。

匿名用户

使用本地存储:

//调整switch_style以使用本地存储

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);
})