我一直花时间使用 javascript 制作这种故障效果。故障效果的工作原理是循环遍历字母表( alpha or alphaCaps variable) 并在某个字母( text variable) 处停止,代码如下:
const text = 'TheThingThatDoesntEndWellWillEndWell'
const alphaCaps = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var output = "";
var progress = 0;
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date <
milliseconds);
}
function glitch() {
while (output != text) {
var randomNums = Math.floor(Math.random() * alpha.length)
if (alpha[randomNums] == text[progress] || alphaCaps[randomNums] == text[progress]) {
output += text[progress];
document.getElementById("text").innerHTML = `${output}`
progress++;
sleep(25);
} else {
document.getElementById("text").innerHTML = `${output}${alpha[randomNums]}`
sleep(25);
}
}
}Run Code Online (Sandbox Code Playgroud)
<h1 id="text"></h1>
<button onclick="glitch()">Glitch Button</button>Run Code Online (Sandbox Code Playgroud)
问题是,当我按下按钮时,它没有显示循环过程。我尝试启用睡眠功能,但不起作用。你们都可以帮我吗...
警告:可能会使您的浏览器崩溃。
你不需要睡觉。它只是挂起浏览器
const text = 'The Thing That Doesn\'t End Well Will End Well'
const alphaCaps = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', "'"];
const alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', "'"];
var output = "";
var progress = 0;
const len = text.length;
function glitch() {
if (progress >= len) {
return;
}
var randomNums = Math.floor(Math.random() * alpha.length)
if (alpha[randomNums] == text[progress] || alphaCaps[randomNums] == text[progress]) {
output += text[progress];
document.getElementById("text").innerHTML = `${output}`
progress++;
} else {
document.getElementById("text").innerHTML = `${output}${alpha[randomNums]}`
}
requestAnimationFrame(glitch);
}
// just to make it nicer
window.addEventListener("load",function() {
document.getElementById("but").addEventListener("click",function() {
this.hidden=true;
glitch();
});
})Run Code Online (Sandbox Code Playgroud)
<h1 id="text"></h1>
<button type="button" id="but">Glitch Button</button>Run Code Online (Sandbox Code Playgroud)