Jquery 在文本中淡出一段时间

Jquery Fade in Text for Certain Time

本文关键字:淡出 一段时间 文本 Jquery      更新时间:2023-09-26

在我的应用程序中,我有一个脚本可以告诉某人何时联机或脱机。我把文本如果有人通过content = name+' went offline'上线/离线,反之亦然。然后,我将该文本放在函数调用结束时的div 中:$('#new').text(content);

问题在于淡出,总而言之,它并没有真正起作用。我一直在尝试玩弄它。这是我到目前为止所拥有的:

$('#new').text(content);
$('#new').fadeIn('slow', function() {
        setTimeout($('#new').fadeOut('slow', function() {
        $('#new').css('display', 'none');   
        }));
    });

调中的display:none是不必要的,fadeOut()结束后会自动将显示设置为 none。

$('#new').text(content);
$('#new').fadeIn('slow', function() {
    setTimeout("$('#new').fadeOut('slow');", 2000);
});

2000 是你想延迟它的毫秒数,把它改成更适合你的值。

正如@Pst评论的那样,函数对象可能更一致,即使我个人对函数对象的问题比代码字符串更多。

您也可以使用函数对象:

$('#new').text(content);
$('#new').fadeIn('slow', function() {
    setTimeout(function(){ $('#new').fadeOut('slow'); }, 2000);
});

您需要记住提供setTimeout在执行操作之前应等待的持续时间。

$("#hello")
  .text(content)
  .fadeIn("slow", function(){
    setTimeout(function(){
      $("#hello").fadeOut();
    }, 2000);
  });

2000 表示 2 秒。如果您希望它保持可见更长时间,请增加此值。

功能演示:http://jsbin.com/aciwon/edit#javascript,html

您是否在$(document).ready()内使用它?如果没有,请按以下方式放置:

$(document).ready(function() {
    $('#new')
        .text(content)
        .fadeIn('slow', function() { 
            setTimeout(function() { $('#new').fadeOut('slow'); }, 2000); 
        });
});

另外,请务必使用display: none初始化您的元素,并注意我已经删除了部分不必要的代码。

你的setTimeout()代码是错误的,你必须向它传递一个函数。

为什么不直接使用延迟?

$("#new").text(content).fadeIn("slow").delay(1000).fadeOut("slow");