简体   繁体   English

在页面上切换选项卡和重新加载时保持动态 CSS

[英]Maintain the dynamic CSS on switching tabs on page and on reload

In my application, there is an option for the user to change the CSS of the page on click of a button.在我的应用程序中,用户可以选择通过单击按钮更改页面的 CSS。 I want that the selected style should remain if the user visits another link on the page or if the page is reloaded, ie the user should not have to select the style/theme of choice again and again.如果用户访问页面上的另一个链接或重新加载页面,我希望选择的样式应该保留,即用户不应该一次又一次地选择 select 样式/主题。

How can I achieve this?我怎样才能做到这一点?

 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>

For storing value you need to add localStorage from browser.为了存储值,您需要从浏览器添加localStorage Here is details about it: https://www.w3schools.com/jsref/prop_win_localstorage.asp这是有关它的详细信息: https://www.w3schools.com/jsref/prop_win_localstorage.asp

Sample code you can use this:您可以使用的示例代码:

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

}

and onload check for localstorage和 onload 检查localstorage

var style_theme = localStorage.getItem("style_theme");
if(!style_theme){
style_theme = "blue" // set default theme which want to.
}
switch_style(style_theme);

Based on this you can call function.基于此,您可以致电 function。

Using Local Storage:使用本地存储:

// tweaking s witch_style to use local storage // 调整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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM