jQuery切换与cookie:如何获取折叠状态默认情况下,仍然可访问? [英] jQuery toggle with cookies: how to get collapsed state by default and remain accessible?

查看:169
本文介绍了jQuery切换与cookie:如何获取折叠状态默认情况下,仍然可访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学者,所以请原谅我无法看到一个明显的解决方案(如果有一个)。也就是说,我已经搜索interweb的答案,并只有同一个问题。我到目前为止的工作:使用我在 http:// www.tobypitman.com/multiple-collapsable-panels-with-cookies/ ,我设法获得多个容器在 display:block display:none ,我使用Klaus Hartl的cookie.js设置cookie。

I am a total beginner, so excuse my inability to see an obvious solution (if there is one). That said, I have scoured the interweb for an answer to this and have only run into the same question. What I've got working so far: using what I found at http://www.tobypitman.com/multiple-collapsable-panels-with-cookies/, I've managed to get multiple containers to toggle between display:block and display:none, and I'm setting cookies with Klaus Hartl's cookie.js.

一切都很棒!除非我想要切换容器的初始状态被关闭。我真的想完成这个没有任何显示:无直接在CSS,所以内容保持可访问与JS关闭。我不是一个程序员,我的暴力方法改变事情在这里,那里,直到发生的事情不是相当削减它。我已经包括HTML,CSS和jQuery所有下面 - 唯一的事情,将缺少我的示例是CSS图像精灵的< h6> 触发器。

Everything works terrifically! Except that I want the toggle containers' initial state to be closed. I'd really like to accomplish this without having any display:none directly in the CSS, so the content remains accessible with JS off. I'm not a programmer, and my brute force method of changing things here and there until something happens is not quite cutting it. I've included the HTML, CSS and jQuery all below - the only thing that will be missing from my example is the CSS image sprite for the <h6> that serves as the trigger.





    
    Toggle with cookie
<style>
    .toggle-wrapper {
        overflow:hidden;
        display:block;
    }

    .toggle-wrapper .toggle-container {
        position:relative;
        overflow: hidden;
    }

    .toggle-wrapper h6.trigger {
        background: transparent url(images/trigger-sprite.png) no-repeat left top;/*sprite is 15x30px - plus sign on top, minus on bottom*/
        height: 15px;/*half of sprite's height*/
        cursor:pointer;
        padding:0 0 0 16px;
        margin:0;
    }

    .toggle-wrapper h6.active {
        background-position: left bottom;/*this is the open state, showing the minus sign part of sprite*/
        padding:0 0 0 16px;
    }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    /**
     * Get the value of a cookie with the given key.
     *
     * @example $.cookie('the_cookie');
     * @desc Get the value of a cookie.
     *
     * @param String key The key of the cookie.
     * @return The value of the cookie.
     * @type String
     *
     * @name $.cookie
     * @cat Plugins/Cookie
     * @author Klaus Hartl/klaus.hartl@stilbuero.de
     */
    jQuery.cookie = function (key, value, options) {

        // key and value given, set cookie...
        if (arguments.length > 1 && (value === null || typeof value !== "object")) {
            options = jQuery.extend({}, options);

            if (value === null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            return (document.cookie = [
                encodeURIComponent(key), '=',
                options.raw ? String(value) : encodeURIComponent(String(value)),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
    };

    // http://www.tobypitman.com/multiple-collapsable-panels-with-cookies/

    $(document).ready(function(){

        $("div.toggle-wrapper h6").addClass("active");

        var l = $('div.toggle-wrapper h6').length;
        var panel = $("div.toggle-wrapper div.toggle-container");

        for (c=0;c<=l;c++){
            var cvalue = $.cookie('panel' + c);
            if ( cvalue == 'closed' + c ) {
                $(panel).eq(c).css({display:"none"});
                $(panel).eq(c).prev().removeClass('active').addClass('inactive');
            };
        };

        $("div.toggle-wrapper h6.active").toggle(
            function () {
                var num = $("div.toggle-wrapper h6").index(this);
                var cookieName = 'panel' + num;
                var cookieValue = 'closed' + num;
                $(this).next("div.toggle-container").slideUp(500);
                $(this).removeClass('active');
                $.cookie(cookieName, cookieValue, { path: '/', expires: 10 }); 
            },
            function () {
                var num = $("div.toggle-wrapper h6").index(this);
                var cookieName = 'panel' + num;
                $(this).next("div.toggle-container").slideDown(500);
                $(this).addClass("active");        
                $.cookie(cookieName, null, { path: '/', expires: 10 });
            }
        );

        $("div.toggle-wrapper h6.inactive").toggle(
            function () {
                var num = $("div.toggle-wrapper h6").index(this);
                var cookieName = 'panel' + num;
                $(this).next("div.toggle-container").slideDown(500);
                $(this).addClass("active");
                $(this).removeClass('inactive');       
                $.cookie(cookieName, null, { path: '/', expires: 10 });
            },
            function () {
                var num = $("div.toggle-wrapper h6").index(this);
                var cookieName = 'panel' + num;
                var cookieValue = 'closed' + num;
                $(this).next("div.toggle-container").slideUp(500);
                $(this).removeClass('active');
                $.cookie(cookieName, cookieValue, { path: '/', expires: 10 }); 
            }
        );

    });
</script>



推荐答案

要创建一个关闭的默认状态,只需让切换容器依赖另一个叫做'open'的cookie。如果没有cookie'open + c',容器也被隐藏。

To create a closed default state, just make the toggle-container depend on another cookie called let's say 'open'. If there is no cookie 'open + c' the container is hidden as well.

if ( cvalue == 'closed' + c || cvalue != 'open' + c ){
  //hide()etc...
}

函数删除slideDown上的面板cookie,但将值设置为open + num的面板cookie。

Now don't make the toggle function remove the panel cookie on slideDown, but set the panel cookie with value 'open + num'.

var cookieValue = 'open' + num; 

$.cookie(cookieName, cookieValue, { path: '/', expires: 10 });

设置open cookie后,脚本的工作方式与以前一样。这是整个事情与不同的类名,但不应该是一个问题。

After setting the open cookie the script works like it did before. Here is the whole thing with different class names but that should not be a problem.

$(document).ready(function(){

// Toggle sliding containers with cookies
$("div.toggle_widget h2.toggle_trigger").addClass("active");

var l = $('div.toggle_widget h2.toggle_trigger').length;

var panel = $("div.toggle_widget div.toggle_container");

for (c=0;c<=l;c++){

   var cvalue = $.cookie('panel' + c);

   if ( cvalue == 'closed' + c || cvalue != 'open' + c ) {

        $(panel).eq(c).css({display:"none"});
        $(panel).eq(c).prev().removeClass('active').addClass('inactive');
   };
};


$("div.toggle_widget h2.toggle_trigger.active").toggle(
      function () {
            var num = $("div.toggle_widget h2.toggle_trigger").index(this);
            var cookieName = 'panel' + num;
            var cookieValue = 'closed' + num;
        $(this).next("div.toggle_container").slideUp(250);
        $(this).removeClass('active');
            $.cookie(cookieName, cookieValue, { path: '/', expires: 10 });  

      },
      function () {
            var num = $("div.toggle_widget h2.toggle_trigger").index(this);
            var cookieName = 'panel' + num;
            var cookieValue = 'open' + num;
            $(this).next("div.toggle_container").slideDown(250);
            $(this).addClass("active");         
        $.cookie(cookieName, cookieValue, { path: '/', expires: 10 });
      }
    );


$("div.toggle_widget h2.toggle_trigger.inactive").toggle(
      function () {
            var num = $("div.toggle_widget h2.toggle_trigger").index(this);
            var cookieName = 'panel' + num;
            var cookieValue = 'open' + num;
            $(this).next("div.toggle_container").slideDown(250);
            $(this).addClass("active"); 
            $(this).removeClass('inactive');        
        $.cookie(cookieName, cookieValue, { path: '/', expires: 10 });

      },
      function () {
            var num = $("div.toggle_widget h2.toggle_trigger").index(this);
            var cookieName = 'panel' + num;
            var cookieValue = 'closed' + num;
        $(this).next("div.toggle_container").slideUp(250);
        $(this).removeClass('active');
            $.cookie(cookieName, cookieValue, { path: '/', expires: 10 });  
      }
    );
});

这篇关于jQuery切换与cookie:如何获取折叠状态默认情况下,仍然可访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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