2011-12-03 20 views
4

我知道的奇怪問題。我試圖讓一個字在一個頁面上逐個字母地加載一小段時間。是的,這是我在工作時編碼時有時會想到的。我嘗試了許多方法,絕對沒有成功。我得到的最好的是帶有下面的代碼的警告框,但我想用頁面上的html來完成。這甚至有可能嗎?是否有可能在用JavaScript延遲的頁面中拼出單詞?

<script type="text/javascript"> 

var foo = "foo bar"; 
foo = foo.length ; 
for(i= 1; i<=foo; i++){ 
    var hello = "FOO BAR"; 
    hello = hello.substring(0, i);  
    alert(hello); 

} 

</script> 

我假設必須有某種類型的設置超時隱藏顯示和一個div加載它?

+0

你可以包含你的html嗎? – jbranchaud

+0

在這個例子中,我沒有放任何東西。我想在div標籤中說出這個拼寫讓我們在html中說。所以像

和附加在這裏的innerhtml拼寫單詞 –

回答

6

假設您想要將「foo bar」加載到該div中,一次加載一個字符,並在其間延遲1秒。

<div id="destination" /> 

$(function() { 
    loadWord("foo bar", 0); 
}); 

function loadWord(word, index) { 
    if (index == word.length) return; 
    $("#destination").text($("#destination").text() + word[index]); 
    setTimeout(function() { loadWord(word, index + 1); }, 1000); 
} 
+3

演示:http://jsfiddle.net/9XkKm/ –

+1

@Jared - 謝謝 - 我需要開始使用小提琴更多。 –

+1

我很喜歡做小提琴,主要是因爲我是一個視覺的,看起來很相信的人,也是因爲實際上在答案中運行代碼會暴露出明顯的錯誤。 –

11

你可以嘗試這樣的事情:

var word = "Hello World"; 

    function nextChar(i){ 
     $("#word").text("The Word is: [" + i + "]" + word.substring(0, i)); 
     if(i < word.length){ 
     setTimeout("nextChar(" + (i + 1) + ")", 1000); 
     } 
    } 

    $(document).ready(function(){ 
    nextChar(0); 
    }); 

和HTML:

<div id="word"></div> 
+2

演示:http://jsfiddle.net/yUeku/ –

1

多一點的jQuery十歲上下answer

他人重大差異(即旁jQuery和一般):
1)動畫
2)上負載DOM操作只
3)預設寬度(不會推其他外)

1

這裏的一個發燒友版本,使一個jQuery插件用於將文本添加到任何對象,並且它在每個連續信變淡。你可以看到它在這裏工作:http://jsfiddle.net/jfriend00/yMJsc/

你這樣稱呼它:

$(".myClass").revealText("The quick brown fox jumped over the fence.", 500); 

而且,這裏是實施jQuery插件的代碼。

$.fn.revealText = function(text, duration) { 
    duration = duration || 250; 
    for (var i = 0; i < this.length; i++) { 
     showNextChar(this[i], 0); 
    } 
    function showNextChar(item, len) { 
     var base = text.substr(0, len); 
     var nextChar = text[len]; 
     // don't fade in a space since it wouldn't be visible 
     var aheadChar = text[len + 1]; 
     if (aheadChar == " ") { 
      nextChar += aheadChar; 
      ++len; 
     } 
     item.innerHTML = base + '<span class="fadeLetter" style="display: none;">' + nextChar + '</span>'; 
     ++len; 
     $(".fadeLetter", item).fadeIn(duration, function() { 
      if (len < text.length) { 
       showNextChar(item, len); 
      } else { 
       item.innerHTML = text; 
      } 
     }); 
    } 
    return(this); 
} 
+0

我真的需要開始學習jQuery的所有不同的技巧。我只是主要用於選擇器。它驚人的多少東西,你可以用它做 –

相關問題