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');
})
You need to add one class in the beginning to element and use toggleClass()
instead:
$('p').toggleClass('displayNone displayBlock');
$('p').toggleClass('displayNone displayBlock');////Adds 'displayNone', removes 'displayBlock' and vice versa
You need to add class to p element:
<p class="displayBlock">
If you want animation : use
opicity
anstransition
together, becausedisplay:none
does not work withtransition
.
Here is demo:
callback
function of slide toogle:
$('button').click(function(){ $('p').slideToggle('normal',function(){ $(this).toggleClass('displayNone displayBlock');}); })
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.