jQuery点击定时通知:实现淡入淡出+高度从0到30px动画需求
Got it, let's tweak your code to get that height animation working alongside the fade in/out! Here's how to do it step by step:
Step 1: Adjust the initial CSS state
First, we need to replace the hide() jQuery call with CSS that sets your element to a height-0, fully transparent state (instead of display:none, which breaks height animations):
#post-draft1 { height: 0; opacity: 0; overflow: hidden; /* Prevents content from leaking out when height is 0 */ /* Remove any existing CSS transitions if they conflict with jQuery animations */ transition: none; }
Step 2: Rewrite the JavaScript animation logic
Instead of using fadeIn()/fadeOut() (which force display:block/none), we'll use jQuery's animate() method to sync the opacity and height changes together:
$(document).ready(function() { // No need for $("#post-draft1").hide() anymore—CSS handles initial state $("#post-button1").click(postNotification); }); function postNotification() { $("#post-draft1") // Animate both opacity (fade in) and height (grow to 30px) simultaneously .animate({ opacity: 1, height: "30px" }, "slow") // Wait 2000ms while the element stays visible .delay(2000) // Animate opacity (fade out) and height (shrink back to 0) .animate({ opacity: 0, height: "0px" }, "slow"); }
Optional: Hide the element completely after animation
If you want the element to stop taking up space once the animation finishes, add a callback to the final animate() call:
.animate({ opacity: 0, height: "0px" }, "slow", function() { // Set display:none only after the shrink/fade animation completes $(this).css("display", "none"); });
How this works:
- We avoid
fadeIn()because it directly toggles the element'sdisplayproperty, which skips any height transition. Usinganimate()lets us control both opacity and height at the same time for smooth, synchronized motion. - The
overflow:hiddenCSS rule ensures your element's content doesn't peek out when its height is 0, keeping the animation clean.
内容的提问来源于stack exchange,提问作者Kyle Underhill
相关产品推荐
相关产品推荐

