不使用.fadeIn()和.fadeOut()淡化div

问题描述 投票:1回答:3

我试图在我的页面中显示一段时间的警报然后隐藏它。

我需要在不使用.fadeIn().fadeOut()的情况下这样做,因为它会改变CSS显示属性并搞砸我的警报。

所以,我发现了这个(jQuery text fade/transition from one text to another?):

$('#container').animate({'opacity': 1}, 1000, function () {
    $(this).text('new text');
}).animate({'opacity': 0}, 1000);

它正在发挥作用。

问题是它显示和隐藏得太快,我需要在消息消失之前将消息保留一段时间。有没有办法在其中添加延迟?

我怎样才能做到这一点?

jquery html css
3个回答
2
投票

所以你可以分步进行。

  • 如果它开始隐藏,您可以继续并更改文本。
  • 更改后,为不透明度设置动画以淡入其中
  • 完成此操作后,延迟下一个动画,无论您希望它显示多长时间。
  • 延迟之后,再次隐藏它

$('#container')
  .text('My error Text')
  .animate({ opacity: 1 }, 1000)
  .delay(3000)
  .animate({ opacity: 0}, 1000);
#container {
  opacity: 0;
  border-color: rgb(64, 32, 32);
  background-color: rgb(128, 32, 32);
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>

1
投票

试试这个:

$('#container').animate({'opacity': 0.5}, 1000).animate({'opacity': 1}, 1000, function () {
    $(this).text('new text');
});

这将使动画花费1秒钟从隐藏到半透明度,然后它将执行第二个动画,您将在其中更改文本,然后从0.5变为完全不透明度。让我知道它是否有效并满足您的需求。

如果您在显示几秒钟后尝试隐藏警报,请执行以下操作:

$('#container').animate({'opacity': 1}, 1000, function () {
   $(this).text('new text');
}).animate({'opacity': 0}, 1000);

1
投票

animate函数将“duration”作为参数,因此代码中的1000表示1千毫秒= 1秒

只需在不透明度1中使用较小的值即可立即显示,而在不透明度中使用较大的值:0

喜欢:

    $('#container').animate({'opacity': 1}, 100, function () {
    $(this).text('new text');
}).animate({'opacity': 0}, 7000);

这将在100毫秒内显示文本,并在7秒内淡出。

© www.soinside.com 2019 - 2024. All rights reserved.