为JS动画文本添加延迟?

时间:2017-05-23 06:55:38

标签: javascript jquery animation typography

所以我有下面的代码用于自动输入文本动画。文本位于图像前面,我希望人们先查看完整图片,然后文本开始"键入"。我想最好的方法是在文本开始动画之前添加2-3秒的延迟,但我不确定该怎么做。

非常感谢帮助。谢谢!

function cursorAnimation() {
  $('#cursor').animate({
    opacity: 0
  }, 'fast', 'swing').animate({
    opacity: 1
  }, 'fast', 'swing');
}
$(document).ready(function() {
  setInterval('cursorAnimation()', 1000);
});

var text = 'TEXT GOES HERE';

$.each(text.split(''), function(i, letter) {
  setTimeout(function() {
    $('#container').html($('#container').html() + letter);
  }, 110 * i);
});

3 个答案:

答案 0 :(得分:0)

尝试使用setTimeout()函数在一段时间后调用函数,即

$(document).ready(function() {
    setTimeout(yourfunction(), 1000); //changes milliseconds as per your need.
})

https://www.w3schools.com/jsref/met_win_settimeout.asp

答案 1 :(得分:0)

Generaly。完成后将延迟代码打包到回调中,并将回调传递给setTimeout方法。用于在对象中工作时保留功能。我重新打算在打包的回调上调用bind(this)

setTimeout(function () {
    console.log("Delayed message");
}.bind(this), 3000);

在你的情况下

function cursorAnimation() {
  $('#cursor').animate({
    opacity: 0
  }, 'fast', 'swing').animate({
    opacity: 1
  }, 'fast', 'swing');
}
$(document).ready(function() {
  setInterval('cursorAnimation()', 1000);
});

var text = 'TEXT GOES HERE';

setTimeout(function () {
    // delayed code
    $.each(text.split(''), function(i, letter) {
    setTimeout(function() {
        $('#container').html($('#container').html() + letter);
    }, 110 * i);
    });
    // end of delayed code
}.bind(this), 3000);

答案 2 :(得分:0)

添加一些任意延迟不是最好的方法。你永远不知道图像在不同类型的网络上加载需要多长时间,有些非常快,有些可能非常慢。

相反,您应该在某些事件上触发代码,例如当图像加载时。您可以在窗口加载时运行代码作为选项,如下所示:

function cursorAnimation() {
  $('#cursor').animate({
    opacity: 0
  }, 'fast', 'swing').animate({
    opacity: 1
  }, 'fast', 'swing');
}
$(document).ready(function() {
  setInterval('cursorAnimation()', 1000);

  $(window).on("load", function(){
    // do here tasks that you want to run after all page assets e.g. images have been loaded
    showText();
  });//window load()
});

function showText() {
  var text = 'TEXT GOES HERE';
  $.each(text.split(''), function(i, letter) {
    setTimeout(function() {
      $('#container').html($('#container').html() + letter);
    }, 110 * i);
  });
}