2017-02-11 109 views
0

當您打開頁面時,它應該輸入一個字母,但是它根本沒有顯示出來。我是一個新手在這個JavaScript的東西。我在製作javascript打字機效果時遇到了麻煩

HTML

<div class="wrap"> 
    <div class="test type" data-text="Hi, my name is John Doe"></div> 
</div> 

CSS

body { 
    font: 16px/20px sans-serif; 
} 


.wrap { 
    width: 500px; 
    margin: 30px auto; 
    text-align: center; 
} 

.test { 
    margin-top: 10px; 
    text-align: left; 
} 

JS

function typeWriter(text, n) { 
    if (n < (text.length)) { 
    $('.test').html(text.substring(0, n+1)); 
    n++; 
    setTimeout(function() { 
     typeWriter(text, n) 
    }, 100); 
    } 
} 

$('.type').click(function(e) { 
    e.stopPropagation(); 

    var text = $('.test').data('text'); 

    typeWriter(text, 0); 
}); 
+0

你想達到什麼目的?你想創建一個函數,將在網站上逐字寫出該句子? –

回答

2

使用這個,我讓它在更少的代碼中工作。 另一件事我所做的是用一些隨機的時間給現實世界的影響..

$(function(){ 
 
    
 
    var txt = $(".type").data("text").split(""); 
 
    txt.forEach(function(chr, i){ 
 
    var rand = Math.floor(Math.random() * 100) + 1; 
 
    setTimeout(function(){ 
 
     $(".type").append(chr); 
 
     },300*(i+1) + rand) 
 
    }) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="test type" data-text="Hi, my name is John Doe"></div>

2

$(function(){ 
 
    function typeWriter(text, n) { 
 
    if (n < (text.length)) { 
 
     $('.test').html(text.substring(0, n+1)); 
 
     n++; 
 
     setTimeout(function() { 
 
     typeWriter(text, n) 
 
     }, 100); 
 
    } 
 
    } 
 

 
    $('.type').click(function(e) { 
 
    e.stopPropagation(); 
 

 
    var text = $('.test').data('text'); 
 

 
    typeWriter(text, 0); 
 
    }); 
 
});
body { 
 
    font: 16px/20px sans-serif; 
 
} 
 

 

 
.wrap { 
 
    width: 500px; 
 
    margin: 30px auto; 
 
    text-align: center; 
 
} 
 

 
.test { 
 
    margin-top: 10px; 
 
    text-align: left; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="wrap"> 
 
    <div class="test type" data-text="Hi, my name is John Doe">Click me</div> 
 
</div>

你需要添加點擊。 (我在div中添加了文本'點我')。

1

您可能會錯過的CDN。

<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
</head>
您的代碼是很好的。