2011-08-29 66 views
2

考虑以下功能:如何将延迟并入每个循环的jQuery中?

$("document").ready(function(){ 
    var echoText = 'Hello world!'; 
    echoText = echoText.split(''); 
    $.each(echoText, function(key, value){ 
     $("#content").append(value); 
    }); 
}); 

这简单重复输入文本。然而,我想要做的是在每个字符之间添加一个延迟,因此它看起来就像是一个缓慢的人类输入。任何想法如何继续?我尝试了谷歌搜索,但迄今为止没有任何帮助。

回答

1

考虑使用setTimeout()功能:

$("document").ready(function(){ 
    var data = 'Hello world!'; 
    var lastIndex = 0; 

    var fnEcho = function() { 
     if (lastIndex < data.length) { 
      $("#content").append(data[lastIndex]); 
      lastIndex++; 

      window.setTimeout(fnEcho, 1000); 
     } 
    } 

    fnEcho(); 
}); 
0
$("document").ready(function(){ 
    var echoText = 'Hello world!'; 
    var currentChar = 0; 
    var intval = setInterval(function(){ 
     var value = echoText.charAt(currentChar); 
     $("#content").append(value); 
     currentChar++; 
     if(currentChar >= echoText.length){ 
      clearInterval(intval); 
     } 
    }, 10); 
}); 

我没有测试过,所以它可能是越野车,但是这是要做到这一点。您可以增加10的值以减慢文本速度。

3

打字机插件

http://onehackoranother.com/projects/jquery/jquery-grab-bag/text-effects.html

使用IKE

$("#my-container").typewriter(); 

您可以从Here

$.fn.typewriter = function() { 
     this.each(function() { 
      var $ele = $(this), str = $ele.text(), progress = 0; 
      $ele.text(''); 
      var timer = setInterval(function() { 
       $ele.text(str.substring(0, progress++) + (progress & 1 ? '_' : '')); 
       if (progress >= str.length) clearInterval(timer); 
      }, 100); 
     }); 
     return this; 
    }; 
+2

+1不重新发明轮子。 –

+0

@Demian - 不要忘记'重新发明轮子'让每一次轮子都变得圆滑! –

+0

@roXon我恳求不同!我看到太多奇怪的形状的重新创造的轮子同意... –

0
$("document").ready(function(){ 
    var echoText = 'Hello world!'; 
    echoText =echoText.split(''); 
    $.each(echoText, function(key, value){ 
    setTimeout(function(){ 
     $("#content").append(value); 
    }, key * 1000); 
    }); 
}); 
0

试试这个:

var printNextChar = function(theStr, pos){ 
    pos = (typeof(pos) == 'undefined') ? 0 : pos; 
    $('#content').append(theStr.substr(pos,1)); 
    ++pos; 
    if(pos <= theStr.length){ 
     setTimeout(function(){printNextChar(theStr,(pos));},300);  
    } 
} 

$("document").ready(function(){ 
    var echoText = 'Hello world!'; 
    printNextChar(echoText); 

}); 

jsFiddle example

0

下面是一个解决方案使用$.animatestep

function SimulateTyping(containerID, data) { 
    var dv = $('#' + containerID), len = data.length; 
    dv.text(""); 
    $({count: 0}).animate({count: len}, { 
     duration: len * 15, 
     step: function() { 
      dv.text(data.substring(0, Math.round(this.count))); 
     } 
    }); 
} 

这样称呼它

SimulateTyping("content", someText); 

演示:http://jsfiddle.net/naveen/JAxU9/