在我的应用程序中,用户可以选择单击按钮来更改页面的 CSS。如果用户访问页面上的另一个链接或重新加载页面,我希望所选样式应保留,即用户不必一次又一次地选择样式/主题。
我怎样才能做到这一点?
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');
}
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
为了存储您需要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);
}
Run Code Online (Sandbox Code Playgroud)
并加载检查 localstorage
var style_theme = localStorage.getItem("style_theme");
if(!style_theme){
style_theme = "blue" // set default theme which want to.
}
switch_style(style_theme);
Run Code Online (Sandbox Code Playgroud)
基于此,您可以调用函数。