在浏览器中存储一个css类 [英] Store a css class on browser

查看:89
本文介绍了在浏览器中存储一个css类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目可以通过点击链接来改变网站主题:

 < ul> 
< li class == contact>< a href =#>联络< / a>< / li>
< li class =facebook>< a href =#> Facebook< / a>< / li>
< li class =twitter>< a href =#> Twitter< / a>< / li>
< li class =rss>< a href =#> Feed Rss< / a>< / li>
< li class =change-theme>< a href =#>更改主题< / a>< / li>
< / ul>

点击< li class =change-主题> 它会触发脚本:

  $('。change-theme')。 click(function(){
$('body')。toggleClass('theme-dark');
});

添加类 theme-dark ,改变网站主题。但是当用户刷新页面时,默认主题会回来。
有一种方法可以存储选择的主题并在浏览器更新时使用它?

解决方案

Localstorage将会为您提供存储数据而不失效日期的可能性:

  $('。change-theme')。click(function (){
$('body')。toggleClass('theme-dark');
if($('body')。hasClass('theme-dark')){
localStorage.setItem('theme','theme-dark');
}
});
$ b $(document).ready(function(){
var theme = localStorage.getItem('theme');
if(theme!==''){
$('body')。addClass(theme);
}
});

鉴于 sessionStorage 一个会话,直到浏览器关闭(用法与 localStorage 相同)。



所有主要浏览器都支持此功能功能,Internet Explorer支持此功能。



注意:只能在Webstorage中存储字符串。



如果您想使用cookie,您可以尝试:

  document.cookie =theme =主题暗; // setter 

  var x = document.cookie; // getter 

参考

webStorage



cookies


My project has the option to change the site theme by clicking on a link:

<ul>
  <li class="=contact"><a href="#">Contact</a></li>
  <li class="facebook"><a href="#">Facebook</a></li>
  <li class="twitter"><a href="#">Twitter</a></li>
  <li class="rss"><a href="#">Feed Rss</a></li>
  <li class="change-theme"><a href="#">Change Theme</a></li>
</ul>

When clicked on the link within the <li class="change-theme"> it's trigger the script:

$('.change-theme').click(function () {
  $('body').toggleClass('theme-dark');
});

It's add the class theme-dark, changing the site theme. But when the user refresh the page, the default theme comes back. There is a way to store the theme chosen and use it even when the browser is updated?

解决方案

Localstorage will provide you a possibilty to store the data without expiration-date:

$('.change-theme').click(function () {
    $('body').toggleClass('theme-dark');
    if($('body').hasClass('theme-dark')){
        localStorage.setItem('theme', 'theme-dark');
    }
});

$(document).ready(function(){
    var theme = localStorage.getItem('theme');  
    if(theme !== ''){      
        $('body').addClass(theme);
    }
});

Whereas sessionStorage will store the data only for one session, until the browser is closed (usage is the same as localStorage).

All major Browser support this feature, the Internet Explorer support this since version 8.

Note: you can only store strings in the Webstorage.

If you want to use cookies instead you can try:

document.cookie="theme=theme-dark"; //setter

and

var x = document.cookie; //getter

Reference

webStorage

cookies

这篇关于在浏览器中存储一个css类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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