[英]Javascript Typewriter effect for multiple lines
我發現了一個很好的打字機效果,當您單擊按鈕時可以打印文本,並且效果很好。 但是,如果我想使用此腳本創建多個打印不同文本的按鈕,則它不起作用。
Javascript:
<script>
var i = 0;
var txt = 'Text goes here';
var speed = 20;
function typeWriter() {
if (i < txt.length) {
document.getElementById("txt").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
</script>
HTML:
<a href="#" onclick="typeWriter()">CLICK HERE</a>
<p id="txt"></p>
您需要修改函數以使其看起來更像這樣(基本上,全局的所有內容都應該是函數的參數)
因此,您還需要稍微更改函數調用 - 請參閱下面的代碼段。
function typeWriter(messageToShow, targetElement, timeBetween, currentPos = 0) { if (currentPos < messageToShow.length) { document.getElementById(targetElement).innerHTML += messageToShow.charAt(currentPos); currentPos++; setTimeout(function() { typeWriter(messageToShow, targetElement, timeBetween, currentPos); }, timeBetween); } }
<button onclick="typeWriter('Hello world', 'demo', 100)">Click me</button> <button onclick="typeWriter('Other message', 'demo2', 100)">click me two</button> <p id="demo"></p> <p id="demo2"></p>
我提供了一個稍微靈活的方法:
首先,創建一個您希望具有打字機效果的字符串數組:
const texts = ['abcdefghijklmnopqrstuvwxyz', '1234567890`-=[]#&;./,\!"£$'];
您可以在上面看到,該數組中有兩個字符串。 接下來循環遍歷字符串。 我通過調用數組的forEach
方法來做到這一點:
texts.forEach(text =>
{
//work happens here
});
因此,對於每個字符串,創建一個div
用a
,點擊,和p
寫英寸
const div = document.createElement('div');
const a = document.createElement('a');
a.setAttribute('href', '#');
a.innerHTML = 'Type writer go!';
div.appendChild(a);
let p = document.createElement('p');
div.appendChild(p);
document.body.appendChild(div);
然后為a
添加一個點擊監聽器,這將啟動打字機效果。
a.addEventListener('click', function(e)
{
e.preventDefault();
nextUpdate(p, 0, text);
});
如您所見,點擊處理程序調用了一個名為nextUpdate
的函數。 此函數設置p
的當前文本並設置下次更新的超時時間。
function nextUpdate(p, index, text)
{
p.innerHTML = text.substr(0, index);
if(index < text.length)
{
setTimeout(nextUpdate, speed, p, index+1, text);
}
}
if
there 檢查字符串是否已完全寫入。 如果沒有,則設置超時以再次調用nextUpdate
,並傳遞相同的參數,但增加了index
參數,該參數告訴函數要讀取多少字符串。
const texts = ['abcdefghijklmnopqrstuvwxyz', '1234567890`-=[]#&;./,\\!"£$']; const speed = 150; //create the document texts.forEach(text => { //create the area that the type writer will go const div = document.createElement('div'); const a = document.createElement('a'); a.setAttribute('href', '#'); a.innerHTML = 'Type writer go!'; div.appendChild(a); let p = document.createElement('p'); div.appendChild(p); document.body.appendChild(div); //set the onclick of the link a.addEventListener('click', function(e) { e.preventDefault(); nextUpdate(p, 0, text); }); }); function nextUpdate(p, index, text) { p.innerHTML = text.substr(0, index); if(index < text.length) { setTimeout(nextUpdate, speed, p, index+1, text); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.