我正在制作一个简单的文字洗牌器,经过一些改组,它会显示原始文本。
HTML可以是这样的:
<div class="title">
<span>H</span>
<span>O</span>
<span>L</span>
<span>A</span>
</div>
使用Javascript:
var lettersArray = ["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 loop;
$(document).ready(function() {
var time = 0;
$(".title").find("span").each(function() {
var obj = $(this);
/*
@Obj,
@Letter,
@NºShuffles
@Frames = time in ms
*/
setTimeout(function() {
shuffleText(obj, obj.text(), 5, 500);
}, time);
time = time + 100;
});
});
function shuffleText(obj, letter, shuffles, frames) {
var i = 0;
loop = setInterval(function() {
console.log("a")
if (i < shuffles) {
var random = Math.floor(Math.random() * (lettersArray.length + 1));
obj.text(lettersArray[random]);
} else {
for (var e = 0; e < lettersArray.length; e++) {
if (letter == lettersArray[e]) {
obj.text(lettersArray[e]);
return false;
}
}
myClear();
}
i++;
}, (frames/shuffles));
}
function myClear() {
window.clearInterval(loop);
}
这可以实现预期的目的,它会在字符串匹配之前对其进行随机播放,但是,它永远不会超出setInterval,这可能会在一段时间后导致页面速度出现问题。
它的作用:
这里我留下包含代码的jsFiddle:https://jsfiddle.net/Lk2z9d4n/
希望你能帮助我解决这个问题,如果有什么可以改进的话,我会非常感激。
答案 0 :(得分:4)
使用break
代替return false
并将loop
变量传递给myClear()
函数。
var lettersArray = ["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 loop;
$(document).ready(function() {
var time = 0;
$(".title").find("span").each(function() {
var obj = $(this);
/*
@Obj,
@Letter,
@NºShuffles
@Frames = time in ms
*/
setTimeout(function() {
shuffleText(obj, obj.text(), 5, 500);
}, time);
time = time + 100;
});
});
function shuffleText(obj, letter, shuffles, frames) {
var i = 0;
var loop = setInterval(function() {
console.log('running');
if (i < shuffles) {
var random = Math.floor(Math.random() * (lettersArray.length + 1));
obj.text(lettersArray[random]);
} else {
for (var e = 0; e < lettersArray.length; e++) {
if (letter == lettersArray[e]) {
obj.text(lettersArray[e]);
//return false;
break;
}
}
myClear(loop);
}
i++;
}, (frames/shuffles));
}
function myClear(loop) {
console.log('clear interval')
window.clearInterval(loop);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="title">
<span>H</span>
<span>O</span>
<span>L</span>
<span>A</span>
</div>
答案 1 :(得分:2)
您在return
中使用IF
,然后尝试清除间隔。
for (var e = 0; e < lettersArray.length; e++) {
if (letter == lettersArray[e]) {
obj.text(lettersArray[e]);
return false; //ends function HERE
}
}
myClear(); //never gets here!!!
在myClear()
之前移动IF
来电。