简体   繁体   English

LocalStorage单击添加/删除类

[英]LocalStorage click add / remove class

I have a working script which adds a background color and saves it local storage. 我有一个工作脚本,可以添加背景色并将其保存在本地存储中。 I would like to convert this into addClass. 我想将其转换为addClass。 I don't know any JS. 我不懂JS。 The issue I came to when changing .css to .addClass is it doesn't remove the previous selected background color. 我将.css更改为.addClass时遇到的问题是它不会删除先前选择的背景色。 Getting body class="c-wit c-rood c-ori" 获得身体class =“ c-wit c-rood c-ori”

Somehow it doesn't work here on Stackoverflow. 在某种程度上,它在Stackoverflow上不起作用。 But maybe someone knows how I can remove the body class and the add the new one. 但是也许有人知道我如何删除body类并添加新的。

 if (localStorage.getItem("background") != null) { getColour = localStorage.background; $('body').css('background', getColour); } $(".c-ori").click(function () { setColour = '#0c1534'; localStorage.removeItem('background'); $('body').css('background', setColour); localStorage.setItem("background", setColour); }); $(".c-wit").click(function () { setColour = '#fff'; localStorage.removeItem('background'); $('body').css('background', setColour); localStorage.setItem("background", setColour); }); $(".c-rood").click(function () { setColour = '#B71C1C'; localStorage.removeItem('background'); $('body').css('background', setColour); localStorage.setItem("background", setColour); }); 
 *{box-sizing:border-box;} html{color:#fff; height:100%;} body{background:#0c1534; margin:0; padding:0; height:100%; transition:0.5s;} .kleur{text-align:center; position:fixed; top:10px; left:15px; z-index:1; height:30px; color:#fff; font-size:8px; font-family:arial;} .kleur div{width:18px; height:18px; line-height:16px; border:1px solid #fff; margin:5px 2px; display:inline-block; cursor:pointer; border-radius:100%; } .c-ori{background:#0c1534;} .c-wit{background:#ffffff; color:#000;} .c-rood{background:#B71C1C;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="kleur"> <div class="c-ori">1</div> <div class="c-wit">2</div> <div class="c-rood">3</div> </div> 

You should also use removeClass to remove previous classname, and addClass to add your new classname. 您还应该使用removeClass删除以前的类名,并使用addClass添加新的类名。

Also, add the classname in the css file and add the relevant background. 另外,在css文件中添加类名并添加相关背景。 For more information see removeClass addClass 有关更多信息,请参见removeClass addClass。

Maybe something like this? 也许是这样的吗? It will overwrite the class name of the body element 它将覆盖body元素的类名称

if (localStorage.getItem("background") != null) {
  getColour = localStorage.background;
  document.body.className = getColour;
}

$(".c-ori").click(function () {
  setColour = "c-ori"
  document.body.className = setColour
  localStorage.setItem("background", setColour);
}); 

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

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