0

ボタンが押されたときに Cookie + クラスを切り替える方法を見つけようとしています。

のクラス名を持つボタンbtn_fixedが押された場合: - Cookie「 fixed
」を「true」に設定します。 Cookie が true に設定されているため、適用されます。 それ以外の場合: - Cookie「fixed」を「false」に設定します (サイトに初めてアクセスするときのデフォルト値)。 - クラス「fixed」を「」から削除します。
<header>


<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 に答える