日/夜切换使用Cookie保存页面刷新 [英] Day/Night Toggle Using Cookie to Save on Page Refresh

查看:57
本文介绍了日/夜切换使用Cookie保存页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题当然是,一旦单击切换,切换Cookie始终为true.有没有一种方法可以检查切换开关是处于活动状态还是非活动状态,并将该状态保存到Cookie中,然后检查页面刷新是否应该激活暗模式?

The problem I'm having of course is the toggle cookie is always true once the toggle is clicked. Is there a way to check whether the toggle is active / inactive and to save that state to a cookie to then check on page refresh if dark mode should be activated?

jQuery(document).ready(function($) {
  $(".toggle").click(function() {
    $(".toggle").toggleClass("active");
    $("body").toggleClass("night");
    $.cookie("toggle", true);
  });

  if ($.cookie("toggle") == "true") {
    $(".toggle").click();
  }
});

body.night {
  background: #00151f;
  color: #fff;
}

.toggle {
  position: absolute;
  top: 40px;
  left: 0px;
  background: #fff;
  border: 2px solid #00151f;
  width: 45px;
  height: 20px;
  cursor: pointer;
  border-radius: 20px;
  transition: 0.5s;
}

.toggle.active {
  background: #00151f;
  border: 1px solid #fff;
}

.toggle:before {
  left: 0px;
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  background: #00151f;
  border-radius: 50%;
  transition: 0.5s;
}

.toggle.active:before {
  left: 27px;
  background: #fff;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle"></div>

推荐答案

问题是因为即使更改状态,您也只能将cookie设置为 true .要解决此问题,请使用 hasClass()确定UI处于哪种状态并相应地设置cookie:

The issue is because you only ever set the cookie to true, even when changing the state. To fix this use hasClass() to determine what state the UI is in and set the cookie accordingly:

jQuery(document).ready(function($) {
  $(".toggle").click(function() {
    $(".toggle").toggleClass("active");
    $("body").toggleClass("night");
    $.cookie("toggle", $(".toggle").hasClass('active'));
  });

  if ($.cookie("toggle") === "true") {
    $(".toggle").addClass("active");
    $("body").addClass("night");
  }
});

> 小提琴示例

这篇关于日/夜切换使用Cookie保存页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆