【发布时间】:2019-11-20 06:10:53
【问题描述】:
我正在尝试构建一些可重用的代码 sn-ps 来创建打字机效果。它隐藏一个段落,然后用一些 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>
【问题讨论】:
标签: javascript parameter-passing