我发现了一个很好的typewriter effect,它可以在你点击按钮时打印文本,它工作得很好。但是,如果我想使用这个脚本创建多个按钮来打印不同的文本,它就不能工作。
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>发布于 2020-03-16 18:01:26
您需要修改函数,使其看起来更像这样(基本上,所有全局的东西都应该是函数的一个参数)
因此,您还需要对函数调用进行一些更改-请参阅下面的代码片段。
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>
发布于 2020-03-16 18:37:57
我提供了一种稍微更灵活的方法:
首先,创建一个字符串数组,该数组包含您希望出现的具有类型写入器效果的字符串:
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检查字符串是否已完全写入。如果没有,则将超时设置为再次调用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);
}
}
https://stackoverflow.com/questions/60702890
复制相似问题