Javascript淡入文本,一次一个单词,适用于一个div,但不能使用多个div



我试图从div中一次淡出一个单词。下面的代码适用于一个div,但是当我有多个div 时,它不会按顺序执行。

这是小提琴: http://jsfiddle.net/zlud/6czap/110/

谁能看到一个明显的问题?任何打印一行接一行的建议将不胜感激。(因此,第二个div 中的文本将在第一个div 完成后打印。

<html>
<div class="example">These are some words that </br> should be faded in one after the other.</div>
<div class="example"> No way some words that </br> should be faded in one after the other.</div>
</html>

JavaScript

var $el = $('.example').map(function () {
return this;
}).get();
$el.forEach(function (eachdiv){
        
var  text = $(eachdiv).text(),
words = text.split(" ");
var html = "";
for (var i = 0; i < words.length; i++) {
    html += "<span>" + words[i] + " </span>";
        $(eachdiv).html(html).children().hide().each(function(i){
           return $(this).delay(i*500).fadeIn(700);``
        });        
    }
});

这个怎么样?

我假设您不需要动画延迟,而是需要它们一个接一个地出现。

var words, $el;
var arrEl = [];
// loop through each div and populate the array with the container (div) element and its text content split
$('.example').each(function(){
    var $this = $(this);
    arrEl.push({el:$this,words : $.trim($this.text()).split(" ")});
    $this.empty();
});
//This will the startup function  
function fadeIn(){
    var len = arrEl.length,  obj = arrEl.shift() || {}; //get the top item from array and remove it from the array using array.shift
    $el = obj.el; //get the container from the item
    words = obj.words; //get the array of words
    //if there are any items in the array start the animation process for this item.
    if(len)  window.setTimeout(transitionElement, 0); 
}
function transitionElement(){
    var wlen = words.length,
    span = $('<span/>', {'class':'hide'}).append(" " + words.shift()); //remove and get the top text string from the word array wrap it in span with a class "hide" which will hide it by default
    window.setTimeout(function(){
        if(wlen)  //if words are available anymore then call show word
           showWord(span);
        else //else call fadeIn to process the next container in the arrEl array of items
            fadeIn();
    },0);
}
function showWord(span){
     span.appendTo($el).fadeIn(500, transitionElement); // append the span to the container with an animation duration of 500ms and in the complete callback of this invoke transitionElement to process the next word or next item. Here there is no delay required since this will invoked only when the transition of first word is completed
}
//Start animation process
fadeIn();

小提琴

  • 淡入() 回调语法
  • Array.shift

Jquerys 动画函数在参数列表中有一个回调。此回调将在动画完成后执行。或者也许是i是通过引用传递的。

你应该一次选择div 来处理,然后继续下一个完成第一个。现在,您将延迟和淡入同时附加到每个div中的每个单词。当第一个div 完成时,通过触发器启动第二个div 的动画或类似的东西?

最新更新