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:
- Iteratively decrease the height of
#lorem1
until it reaches 0 - Set
#lo开发者_Python百科rem1
todisplay:none;
- Set
#lorem2
todisplay:block; height:0;
- 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.
I think .slideDown() and .slideUp() will do that for you: http://api.jquery.com/slideDown/
精彩评论