保存切换类Div(带本地存储)

时间:2017-09-17 07:14:57

标签: javascript jquery html css

所以我有一个带有div的基本classtoggle的示例,但是我可以将它设置为"活跃class"可以通过刷新/重新打开来保持切换状态。这可以吗?



function myfunc(div) {
  var className = div.getAttribute("class");
  if(className=="normal") {
    div.className = "active";
  }
  else{
    div.className = "normal";
  }
}

.normal /*Default*/
{width:25%; height:25%; background: #ffeb00;}

.active /*Switch*/
{width:25%; height:25%; background: #ff00e2;}

<html>
    <head>
        <title>Test</title>
        <link rel = "stylesheet" type = "text/css" href = "style.css" />
    </head>
    <body>
        <div id="div" class="normal" onclick="myfunc(this)"></div>
        <script src=".jquery-3.2.1.min.js"></script>
        <script src="script.js"></script>
    </body>
</html>
&#13;
&#13;
&#13;

感谢您将来的所有答案。

2 个答案:

答案 0 :(得分:0)

与此类似的东西,尚未经过测试,但这将使您走上正确的轨道(请注意,由于沙箱化,代码段无法在堆栈溢出上运行)

function localStorageExists() {
  if (typeof(Storage) !== "undefined") {
    return true;
  }
  return false;
}

if (localStorageExists()) {
  myfunc(document.getElementById('div'));
}

function myfunc(div) {
  var className = div.getAttribute("class");
  if (className == "normal" || (localStorageExists() && localStorage.getItem('someKey') == 'active')) {
    div.className = "active";
    localStorage.setItem('someKey', 'active');
  } else if (className == "active" || (localStorageExists() && localStorage.getItem('someKey') == 'normal')) {
    div.className = "normal";
    localStorage.setItem('someKey', 'normal');
  }
}
.normal
/*Default*/

{
  width: 25%;
  height: 25%;
  background: #ffeb00;
}

.active
/*Switch*/

{
  width: 25%;
  height: 25%;
  background: #ff00e2;
}
<html>

<head>
  <title>Test</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div id="div" class="normal" onclick="myfunc(this)"></div>
  <script src=".jquery-3.2.1.min.js"></script>
  <script src="script.js"></script>
</body>

</html>

答案 1 :(得分:0)

  

使用localStorage保留最后一个课程

try jsfiddle

 $("#div").addClass(localStorage.getItem('ClassName')) ;

 $("#div").on("click",function(){
      if($(this).hasClass('active')){
           $(this).removeClass("active").addClass("normal");
           localStorage.setItem('ClassName', 'normal');
       }
       else{
           $(this).removeClass("normal").addClass("active");
           localStorage.setItem('ClassName', 'active');
       }
  });