简体   繁体   中英

Using jQuery slideToggle() without display:none?

I'm trying to use jQuery's slideToggle function to show or hide a panel which has been hidden using CSS position, rather than display:none (as this causes issues with a Google Map in one of my panels).

At the moment I'm just hiding and showing the panels like so, but some animation would be nice:

$('.panel').addClass('hidden');
$('.head > span').addClass('closed');

$('.head').click(function() { 
    $(this).next('.panel').toggleClass('hidden');
    $(this).children('span').toggleClass('open');
});

Any ideas?

slideToggle animates height of the element in question apart from visibility. Not sure how exactly you have used CSS position to show/hide your panels. Based on that you have to build you own animation using animate function. Another quick way could be to

For showing element:

  1. Hide the element (using jquery hide())

  2. Apply your class to show element (ie to adjust its position)

  3. Now apply slideDown

For hiding content:

  1. Apply slideUp - use callback function to do steps 2 & 3

  2. Apply your class to hide element (ie to adjust its position outside window)

  3. Show the element (using jquery show())

Edit : Illustrative code goes below (assuming that 'hidden' classes will do CSS positioning to hide the element):

function customSlideToggle(e)
{
   var show = e.hasClass('hidden');
   if (show) {
     e.hide();
     e.removeClass('hidden')
     e.slideDown('slow');
   }
   else
   {
     e.slideUp('slow', function() {
        e.addclass('hidden');
        e.show();
     });
   }
}

slideToggle() is an alternative to toggle() , which shows/hides the selected items depending on its current visible state.

You needn't worry about the classes at all if you are simply trying to get the animation to work.

So, just try the following to see what you get:

$(this).next('.panel').slideToggle();

Try this Pezholio

 $('.head').click(function() {
    $(this).next('.panel').slideToggle('slow', function() {
        $(this).toggleClass('hidden')
    });
    $(this).children('span').slideToggle('slow', function() {
        $(this).toggleClass('open')
    });
});​

you can combine few more effect slideUP,slideDown,slideToggle and with easing plugin you have even add some smoothness to animation

Here is an example

Html

<p class="text">
    test one<br />
    test one<br />
    test one<br />
    test one<br />
    test one<br />

</p>
<span class="more">show</span>​

javascript

$(document).ready(function() {
    $('span.more').click(function() {
        $('p:eq(0)').slideToggle();
        $(this).hide();
    });
});​

CSS

.text{display:none}

​ live demo

http://jsfiddle.net/gB6np/

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