2010-06-28 8 views
2

아래의 코드 샘플을 사용하여 jQuery 쿠키 플러그인을 활용하여 각 div 요소의 토글 상태가 브라우저 세션을 초과하여 지속될 수 있습니다.쿠키로 div 토글 상태 유지하기

감사합니다.

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
    <head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

     <script type="text/javascript"> 

     jQuery.fn.slideFadeToggle = function(speed, easing, callback) { 
     return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback); 
     }; 

     $(document).ready(function(){ 
     $('.toggle').show(); 
     $('.hide').click(function(){ 
      var t = $(this); 
      // toggle hidden div 
      t.parent().find('.toggle').slideFadeToggle(400, function(){ 
      // determine which image to use if hidden div is hidden after the toggling is done 
      var imgsrc = ($(this).is(':hidden')) ? 'http://i47.tinypic.com/vg0hu0.gif' : 'http://i45.tinypic.com/281tsle.gif'; 
      // update image src 
      t.attr('src', imgsrc); 
      }); 
     }) 
     }) 
     </script> 

     </head> 
     <body> 

     <div class="wrapper"> 
     <img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 1 
     <div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> 
     </div> 

     <p> 
     <div class="wrapper"> 
     <img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 2 
     <div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> 
     </div> 
     </p> 
     </body> 
    </html> 

답변

0

무엇이 필요한지 먼저 생각하면 가장 먼저해야 할 일은 "래퍼"섹션 각각에 ID를 부여하는 것입니다. 이 ID는 페이지 뷰 전체에서 토글 가능한 섹션을 식별합니다. id 특성과 같을 필요는 없지만 래퍼 ID가 div.wrapper 요소의 id 특성 값과 같으면 가장 쉽습니다.

그러면 모든 섹션을 처음에 볼 수있게하려는 경우 쿠키에 이 숨겨진 섹션 ID 목록을 저장할 수 있습니다.. 이렇게하면 쿠키가 없으므로 숨겨진 섹션이 없으므로 모든 섹션이 처음에 표시됩니다.

사용자가 섹션을 숨길 때마다 새로 숨겨진 섹션의 ID를 포함하도록 쿠키 값을 업데이트합니다. 사용자가 섹션을 숨김 해제 할 때마다 쿠키 값을 업데이트하여 현재 표시되는 섹션의 ID를 제외합니다.

마지막으로 페이지로드시 쿠키의 ID를 반복하여 나열된 섹션을 숨 깁니다. 여기

당신이 시작하는 데 도움이되는 코드입니다

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type="text/javascript" src="jquery.cookie.js"></script> 
<script type="text/javascript"> 

jQuery.fn.slideFadeToggle = function(speed, easing, callback) { 
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback); 
}; 

/** 
* \returns an array of section IDs 
*/ 
function getHiddenSectionIDs() 
{ 
    var arr = ($.cookie('hidden_section_ids') || '').split(','); 
    for (var i = 0; i < arr.length; ++i) { 
     arr[i] = $.trim(arr[i]); 
     if (arr[i].length <= 0) 
      arr[i] = null; 
    } 
    return arr; 
} 

function setHiddenSectionIDsCookie(hiddenSectionIDs) 
{ 
    var str = ''; 
    for (var i = 0; i < hiddenSectionIDs.length; ++i) { 
     var id = hiddenSectionIDs[i]; 
     if (id !== null) 
      str += ',' + id; 
    } 

    $.cookie('hidden_section_ids', str); 
} 

function toggle(t, updateCookie) { 
    var t = $(t); 
    var parent = t.parent(); 

    // toggle hidden div 
    parent.find('.toggle').slideFadeToggle(400, function(){ 
     // determine which image to use if hidden div is hidden after the toggling is done 
     var imgsrc = ($(this).is(':hidden')) ? 'http://i47.tinypic.com/vg0hu0.gif' : 'http://i45.tinypic.com/281tsle.gif'; 
     // update image src 
     t.attr('src', imgsrc); 

     if (updateCookie || updateCookie === undefined) { 
      var hiddenSectionIDs = getHiddenSectionIDs(); 
      if (parent.find('.toggle').is(':hidden')) 
       hiddenSectionIDs.push(parent.attr('id')); 
      else { 
       for (var i = 0; i < hiddenSectionIDs.length; ++i) { 
        var id = hiddenSectionIDs[i]; 
        if (id == parent.attr('id')) 
         hiddenSectionIDs[i] = null; 
       } 
      } 

      setHiddenSectionIDsCookie(hiddenSectionIDs); 
     } 
    }); 
} 

$(document).ready(function(){ 
    var hiddenSectionIDs = getHiddenSectionIDs(); 
    for (var i = 0; i < hiddenSectionIDs.length; ++i) { 
     var id = hiddenSectionIDs[i]; 
     if (id !== null) { 
      var section = $('#' + hiddenSectionIDs[i]); 
      if (section) { 
       toggle(section.find('.hide'), false); 
      } 
     } 
    } 

    $('.hide').click(function(){ 
     toggle(this); 
    }); 
}); 
</script> 

</head> 
<body> 

<div id="section-1" class="wrapper"> 
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 1 
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> 
</div> 

<p> 
<div id="section-2" class="wrapper"> 
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 2 
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> 
</div> 
</p> 
</body> 
</html> 

그것은 고급/연마 솔루션에서 멀리,하지만 난 그것을 테스트 한, 그것은 작동합니다.

나는 this jQuery cookie plug-in을 사용했습니다.

+0

답장을 보내 주셔서 감사 드리며 프로세스의 "흐름"을 알고 있습니다. 부족한 부분은 코드 예제가 어떻게 구현되었는지 보여줍니다. – Sandra

+0

@Sandra : 저는 답을 추가 한 예제를 작성하고있었습니다. 기본 아이디어를 보여줍니다. –

+0

죄송합니다. 마지막 질문이 하나 있습니다. div가 접힌 상태로 설정된 다음 페이지를 새로 고치면 토글 애니메이션이 실행되어 div가 확장 된 상태에서 접힌 상태로 바뀌 었음을 보여줍니다. 내가 잘못했거나 설계 상으로는 무엇입니까? – Sandra