简体   繁体   中英

Expanding content with jQuery (accordion technique)… quick question

This may be a bit silly question, but I just started doing pretty things in jQuery and I suddenly wondered how to solve a problem that I never even bothered looking into without the help of frameworks.

Suppose we have two div elements:

<body>
    <div id="lorem1" style="display:block; height:400px;">
        Lorem ipsum...
    </div>
    <div id="lorem2" style="display:hidden;">
        dolor sit amet...
    </div>
</body>

Now if we wanted to use an accordion effect to shrink the first div out of existence and grow the second one into existence, I'd assume we'd have the following simple logic:

  1. Iteratively decrease the height of #lorem1 until it reaches 0
  2. Set #lorem1 to display:none;
  3. Set #lorem2 to display:block; height:0; display:block; height:0;
  4. Iteratively increase the height of #lorem2

Then the problem... Increase the height of lorem2... until when? How do we know the final height of our element? We clearly can't pick a static value like "increase it until it reaches 400px", because the content of lorem2 might be more than 400 pixels tall. Alternatively if it's less than 400 pixels then any background colors/images or other elements on the page may not look right.

So how do we figure out when to stop our accordion?

using jQuery you could use the handy toggle attribute:

$('#lorem').animate({
  height: 'toggle'
});

I'm sure other js-libraries offer similar possibilities.


EDIT : Another approach would be animating the object until a height of auto . Or don't hide it via CSS, get the dimensions of the object via JS and hide it afterwards using JS. Now you know the dimensions to show it again.

我认为.slideDown()和.slideUp()将为您做到这一点: http ://api.jquery.com/slideDown/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM