移除class时实现不同过渡:通知框仅淡出不移动
解决通知框仅淡出不向上移动的问题
嘿,我明白你的需求了——你希望通知框在5秒后移除show类时,只淡出消失而不会向上移动,还不想额外添加新的class。咱们先看看问题出在哪:
你的原CSS里,.note的transition同时绑定了top和opacity两个属性。当移除show类时,top会从50%变回初始的0%,这就导致了通知框向上移动的动画。要实现仅淡出的效果,我们只需要调整CSS的定位和过渡逻辑就行。
修改后的完整代码
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="notify">click here</button> <div class="note">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
CSS
.note { top: 50%; /* 固定top在垂直居中位置 */ width: 300px; position: fixed; background: #ccc; padding: 10px; left: 50%; height: 100px; margin: -50px 0 0 -150px; /* 保持水平垂直居中 */ opacity: 0; transition: opacity 1.5s ease; /* 只对透明度设置过渡 */ transform: translateY(-100%); /* 初始状态向上移出视口 */ } .show { opacity: 1; transform: translateY(0); /* 显示时回到居中位置 */ }
JavaScript
$('.notify').click(function() { $('.note').addClass('show'); setTimeout(function() { $('.note').removeClass('show'); }, 5000); })
为什么这样改?
- 我们把
top属性固定为50%,不再用它来控制显示/隐藏,而是改用transform: translateY()来控制位置:初始状态让通知框向上移出视口,添加show类时让它回到居中位置。 - 过渡属性只保留
opacity,这样移除show类时,只有透明度会平滑变化,位置始终保持在垂直居中的位置,完美实现仅淡出的效果。
如果你想保留原有的top写法,还有一种替代思路(不过更推荐上面的流畅方案):
.note { top: 0%; width: 300px; position: fixed; background: #ccc; padding: 10px; left: 50%; height: 100px; margin: -50px 0 0 -150px; opacity: 0; transition: opacity 1.5s ease; /* 默认只过渡透明度 */ } .show { top: 50%; opacity: 1; transition: top 1s ease, opacity 1.5s ease; /* 显示时同时过渡位置和透明度 */ }
这个写法的原理是:添加show类时会触发位置+淡入的动画,移除show类时,因为.note默认只过渡透明度,top会直接回到初始位置——不过这个方式会有轻微的位置跳跃,体验不如第一种方案。
内容的提问来源于stack exchange,提问作者Arun Mahadik
相关产品推荐
相关产品推荐

