问题
Is there a way to animate the CSS display property in jQuery? I have the following:
$(".maincontent").css("display","block");
and want it to do something like this:
$(".maincontent").animate({"display": "block"}, 2500);
回答1:
Just use .show() passing it a parameter:
$(".maincontent").show(2500);
Edit (based on comments):
The above code fades in the element over a 2.5 second span. If instead you want a 2.5 second delay and then want the element to display, use the following:
$(".maincontent").delay(2500).fadeIn();
If, of course, you want a delay and a longer fade, just pass the number of milliseconds desired into each method.
回答2:
You could do something like this:
$("div").css({
"opacity":"0",
"display":"block",
}).show().animate({opacity:1})
Example: http://jsfiddle.net/charlescarver/g7z6m/
This takes into account the display:none, since it will still be removed from the flow of the page until the code is invoked, where it will display it, then set it's opacity to 0. It will then animate it's opacity to 1 when you call the code.
回答3:
Try this (as I mentioned in comments):
You can use .delay() method. I.E:
$(".maincontent").delay(2500).show();
回答4:
Animating opacity using jQuery is more viable than display property, here the opacity is animated from 0 to 1 in 1 second:
$(".maincontent").animate({opacity:1},1000)
Then the css should be like this:
.maincontent{
opacity: 0;
}
If you are planning to hide the entire block before the transistion, you could have a display property.
.maincontent{
opacity: 0;
display: none;
}
Then to show the block with animation:
$(".maincontent").show().animate({opacity:1},1000 function(){
(callback function here)
})
Hope this helps!
来源:https://stackoverflow.com/questions/17863490/animate-css-display