简体   繁体   中英

Remove display:none from slideToggle in jQuery

I am using slideToggle jQuery function.which adds display: none to the element.

But i need to add/remove classes(.displayNone/.displayBlock ) instead of adding style="display:block/display:none to the element.

How to achieve it?.

$('button').click(function(){
    $('p').slideToggle('normal');
})

jsFiddle

You need to add one class in the beginning to element and use toggleClass() instead:

$('p').toggleClass('displayNone displayBlock');

Working Demo

.toggleClass()

$('p').toggleClass('displayNone displayBlock');////Adds 'displayNone', removes 'displayBlock' and vice versa

You need to add class to p element:

<p class="displayBlock">

DEMO

If you want animation : use opicity ans transition together, because display:none does not work with transition .

Here is demo:

Transition Demo

Update


Animation with added and removing class with callback function of slide toogle:

 $('button').click(function(){ $('p').slideToggle('normal',function(){ $(this).toggleClass('displayNone displayBlock');}); }) 

DEMO

Manwal's answer did not include removing the display:none / display:block that .slideToggle() adds. Although removeAttr('style') works (as in the OP's updated fiddle ), it also resets any another inline styles on the element.

You can reset the display rule without affecting any other inline styles by setting it to '' .

Here is a revised version:

$('button').click(function(){
    $('p').slideToggle('normal', function() {
      $(this).css('display', '').toggleClass('displayNone displayBlock');
    });
});

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