在页面刷新后保持切换类 [英] Keeping toggled class after page refresh

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

问题描述



我基本上有一个第二个body类别使用不同的字体为整个网站,当客户端单击链接更改字体时访问。理想情况下,这不会是逐页的,但是新类在访问新页面后会粘贴。我的更改类代码通过jquery看起来像这样:

  $(document).ready(function(){
$ (a#switcher)。click(function(){
$(body)。toggleClass(alternate_body);
});
});

有比较简单的方法吗?提前感谢。

解决方案

Cookie方法



jQuery插件(如 jquery-cookie )以简化Cookie访问。所以你的代码会成为这样保存类设置:

  $(document).ready(function b $ b var body_class = $ .cookie('body_class'); 
if(body_class){
$('body')。attr('class',body_class);
}
$(a#switcher)。click(function(){
$(body)。toggleClass(alternate_body);
$ .cookie('body_class',$ 'body')。attr('class'));
});
});



网址参数



在页面上点击 #switcher 时在所有链接上设置网址参数,以便在不设置Cookie的情况下维护状态。


am thinking this has been done many times before but despite reading some posts about cookies couldn't get my head round it.

I basically have a second body class with different fonts for the whole site which is accessed when the clients clicks a link to change font. Ideally this wouldn't be on a page-by-page basis but the new class would 'stick' after a new page is visited. My change class code via jquery looks like this:

$(document).ready(function() {
    $("a#switcher").click(function() {
        $("body").toggleClass("alternate_body");
    });
});

Is there a relatively simple way of achieving this? Thanks in advance.

解决方案

Cookie approach

You can use a jQuery plugin such as jquery-cookie to simplify cookie access. So your code would become something like this to save the class setting:

$(document).ready(function() {
    var body_class = $.cookie('body_class');
    if(body_class) {
        $('body').attr('class', body_class);
    }
    $("a#switcher").click(function() {
        $("body").toggleClass("alternate_body");
        $.cookie('body_class', $('body').attr('class'));
    });
});

URL Parameters

Another option would be to set a URL parameter on all the links the page when they click #switcher to maintain the state without setting a cookie.

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

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