[英]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.