我正在尝试构建一些可重复使用的代码片段,以创建打字机效果。它隐藏一个段落,然后用一些js代码将其替换为另一个段落,该代码一次打印一个字符。我正在尝试制作可重复使用的段落ID和文本参数,但是我无法让这些参数通过我的函数。到目前为止,一些非常乐于助人的人为我提供了帮助,但是我无法弄清楚这最后一步。
我将同时附上我的函数,然后再附上没有参数。任何帮助将不胜感激。
<body>
<div class="style typeClick">
<p id="remove">Hide Me</p>
<p id="type"></p>
</div>
</body>
<style>
.style {
height: 2em;
width: 100%;
background-color: white;
}
body{
background-color: lightgrey;
}
.hide {
display: none;
}
</style>
<script>
/* ---------- DOESNT WORK AS EXPECTED ---------- */
(() => {
function hideInitText() {
let hide = document.getElementById("remove");
hide.classList.add("hide");
}
hideInitText();
//make a parameter that will take each id through it
const typeWriter = ((id, text) => {
let letCounter = 0;
return () => {
let cycle, classCounter;
let typewriter = text;
let speed = 50;
//Cycle through each id after done
cycle = document.querySelectorAll(id);
for (classCounter = 0; classCounter < cycle.length; classCounter++) {
typeOut();
}
function typeOut() {
if (letCounter < typewriter.length) {
cycle[classCounter].innerHTML += typewriter.charAt(letCounter);
letCounter++;
setTimeout(typeWriter, speed);
}
}
};
})();
document.querySelector('.typeClick').addEventListener('click', function() {typeWriter("#type", "type out text")});
})();
/* ---------- WORKS AS EXPECTED ---------- */
(() => {
function hideInitText() {
let hide = document.getElementById("remove");
hide.classList.add("hide");
}
hideInitText();
//make a parameter that will take each id through it
const typeWriter = (() => {
let letCounter = 0;
return () => {
let cycle, classCounter;
let typewriter = "Type out text";
let speed = 50;
//Cycle through each id after done
cycle = document.querySelectorAll("#type");
for (classCounter = 0; classCounter < cycle.length; classCounter++) {
typeOut();
}
function typeOut() {
if (letCounter < typewriter.length) {
cycle[classCounter].innerHTML += typewriter.charAt(letCounter);
letCounter++;
setTimeout(typeWriter, speed);
}
}
};
})();
document.querySelector('.typeClick').addEventListener('click', typeWriter());
})();
</script>
[使用((id, text) => {})()
时,该函数以零参数调用。如果要为此功能提供参数,请不要使用IIFE或(id, text) => { ((id, text) => {})(id, text) }
。
https://codepen.io/1010543618/pen/MWWLxmN?editors=0110
const typeWriter = (selector, text) => {
let letCounter = 0;
let cycle, classCounter;
let typewriter = text;
let speed = 50;
//Cycle through each id after done
cycle = document.querySelectorAll(selector);
function typeOut() {
if (letCounter < typewriter.length) {
for (classCounter = 0; classCounter < cycle.length; classCounter++) {
cycle[classCounter].innerHTML += typewriter.charAt(letCounter);
letCounter++;
}
setTimeout(typeOut, speed);
}
}
typeOut();
};