0

我试图找出一种方法,以便在按下按钮时切换 cookie + 类。

如果:按下类名为的按钮btn_fixed
- 将 cookie “fixed”设置为“true”,
- 将类添加到<header>名为“fixed”的“”中,同样当页面加载时,类“fixed”是已应用,因为 cookie 设置为 true
Else:
- 将 cookie "fixed" 设置为 "false" (默认值,当第一次进入站点时),
- 从 " " 中删除类 "fixed <header>"

这是我到目前为止所得到的,我现在可以看到它与我想要它做的相去甚远:

if (jQuery.cookie("fixed") != "true") {  
        jQuery('a.fixed_btn').click(function () {  
            jQuery('header').addClass('fixed');  
            jQuery.cookie("fixed", "true");  
        });  
    }  
    else  
    {  
        jQuery('a.fixed_btn').click(function () {  
            jQuery('header').removeClass('fixed');  
    jQuery.cookie("fixed", "false");
    }  



<a href="#" class="fixed_btn">Fixed/Fluid</a>  
<header>aaa</header>​

http://jsfiddle.net/UWLdq/7/

谢谢你的帮助。

4

3 回答 3

1

这个怎么样:

$(document).on('click','a.fixed_btn',function(){   
    var fixed = jQuery.cookie("fixed");              
    jQuery('header').toggleClass('fixed');
    jQuery.cookie("fixed", fixed === "true" ? "false" : "true");

})

http://jsfiddle.net/UWLdq/5/

于 2012-11-30T18:51:17.660 回答
1

您最初只需要切换类,然后绑定一个单击事件即可。

jQuery(document).ready(function($) {
    // set class initially based on current cookie value
    $('.cookiefixed').toggleClass('fixed', $.cookie("fixed") == "true");
    // on click, toggle both class and cookie value
    $('a.fixed_btn').click(function() {
        $('.cookiefixed').toggleClass('fixed');
        $.cookie("fixed", $('.cookiefixed').hasClass('fixed'));
    });
});​

我建议不要'header'用作选择器,因为一个页面上可以有多个标题,我怀疑你是否希望他们都获得这个类。

演示:http: //jsfiddle.net/UWLdq/6/

于 2012-11-30T18:52:25.913 回答
0

根据 Bluetoft 的回答,您还需要在页面加载时检查 cookie。

小提琴

$(document).on('click','a.fixed_btn',function(){   
    var fixed = jQuery.cookie("fixed");              
    jQuery('header').toggleClass('fixed');
    jQuery.cookie("fixed", fixed === "true" ? "false" : "true");

});

if ($.cookie("fixed") != "true") {
    $('header').addClass('fixed');
}else{
    $('header').removeClass('fixed');
}
于 2012-11-30T18:57:40.977 回答