开发者

jQuery: Toggle height on multiple sections with one function

开发者 https://www.devze.com 2023-03-23 01:35 出处:网络
I have multiple sections, three to be exact, of varying heights with a basic layout of: <section>

I have multiple sections, three to be exact, of varying heights with a basic layout of:

    <section>
       <h2>My heading</h2>
    </section>

I'm looking for a way to show them initially, but then when the user clicks on the <h2>, to have that section decrease to a height of 68px. The main problem is that each section is a different height(i.e the first is 478px, the second 2118px, and the third 247px), but I don't want to write a separate function for each section and was hoping to do it all in one. It was working fine until I closed the first section and instead of re-opening it, click on the second section's <h2>. That's where the problems began. So my question is, is there anyway to do this or do I need a separate function for each section?

sectionSize = "normal";
$(document).ready(function(){
  //var sectionSize = "normal";
  $("h2").click(function(){
     var parentSection = $(this).parents("section");      
    if (sectionSize == "normal") {
      sectionHeight = parentSection.height();
      parentSection.animate({height:"68px"},"fast"),
      sectionSize = "collapsed";
    } else {
      parentSection.animate({height:sectionHeig开发者_运维技巧ht},"fast"),   
      sectionSize = "normal";
    }
  });
});

I have a fuller version here http://jsfiddle.net/Skooljester/94yqX/ with the HTML and CSS further fleshed out.


Rather than store the height in a global variable (generally bad to use global variables anyway). Store it against the element using the data() function of jquery:

var parentSection = $(this).parents("section");   
var sectionSize = $(this).data('sectionSize') || "normal";   
if (sectionSize == "normal") {
    $(this).data('sectionHeight' parentSection.height());
    parentSection.animate({height:"68px"},"fast"),
    $(this).data('sectionSize', 'collapsed');
 }
 else {
     parentSection.animate({height:$(this).data('sectionHeight')},"fast"),   
     $(this).data('sectionSize', 'normal');
 }

Updated with full code for click function


Check out slideToggle();

http://api.jquery.com/slideToggle/

I would create a container with a class below your H2 tags, like:

 <h2>Header</h2>
 <div class="slideThis">
 some content
 </div>

Then,

write some jQuery similar to this:

 $('h2').click(function(){
       $(this).next('.slideThis').slideToggle('slow');
 });

OR......

Look into setting up your page using jQuery UI Accordion

http://jqueryui.com/demos/accordion/


You can store the default height in the section so that you know on each click where to set the height of that section. I've gotten it working in this jsFiddle : http://jsfiddle.net/uchV3/

0

精彩评论

暂无评论...
验证码 换一张
取 消