jQuery - 页面重新加载后继续添加 onclick css [英] jQuery - keep added onclick css after page reload

查看:33
本文介绍了jQuery - 页面重新加载后继续添加 onclick css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面中添加了 jQuery 的 css,以使访问者可以通过单击按钮来更改对比度.

I added css by jQuery to my page to enable visitors changing the contrast by clicking button.

但我想在重新加载页面后保持 css 处于活动状态(当已单击对比按钮时).我希望这是可能的,因为我还没有找到任何解决方案.

But I would like to keep css active after reloading the page (when contrast button is already clicked). I hope it is possible, because I didn't find any solution yet.

我的代码:

var applied = false;

$('.contrast-on').click(function() {
  if (!applied) {
    $('*').css('background-color', 'rgb(0, 0, 0)').css('color', 'rgb(255, 255, 255)').css('background-image', 'none');
    applied = true;
  } else {
    $('*').css('background-color', '').css('color', '').css('background-image', '');
    applied = false;
  }
});

访问者不必每次都在我网站上的每个页面/帖子上单击对比按钮,这一点很重要.

It is important that visitor will not have to click contrast button every time on every pages/posts on my site.

推荐答案

尝试使用 localStorage 实现此目的.

Try to use localStorage for this purpose.

var applied = localStorage.getItem("applied") == "true";
if (applied) {
  $('*').css('background-color', 'rgb(0, 0, 0)').css('color', 'rgb(255, 255, 255)').css('background-image', 'none');  
} else {
  $('*').css('background-color', '').css('color', '').css('background-image', '');
}

$('.contrast-on').click(function() {
  if (!applied) {
    $('*').css('background-color', 'rgb(0, 0, 0)').css('color', 'rgb(255, 255, 255)').css('background-image', 'none');
    applied = true;    
  } else {
    $('*').css('background-color', '').css('color', '').css('background-image', '');
    applied = false;
  }
  localStorage.setItem("applied", applied);
});

注意:这不会保存浏览器重启的结果.如果您想要长期解决方案,请使用 DB 或 cookie.

Note: this will not save result for browser restart. If you want long-term solution, use DB or cookies.

这篇关于jQuery - 页面重新加载后继续添加 onclick css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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