我正在尝试制作模式匹配算法的动画。根据文本和图案的字符是否匹配,字符会变成红色或绿色,并且图案会继续移动。我的问题是图案沿着文本移动得太快,没有足够的时间来显示图案和文本匹配或不匹配。
对我来说,尝试实现动画的最佳方法是什么,其中算法检查字符是否匹配,更新背景颜色,然后检查下一个字符或移动图案?
function animatePattern(boxWidth, shiftpos) {
$("#pattern_array").animate({left: boxWidth * shiftpos});
}
function turnRed(x, y) {
$(x + y).animate({backgroundColor: "#db1a35"});
}
function turnWhite(x, y) {
$(x + y).animate({backgroundColor: "#fff"});
}
function turnGreen(x, y) {
$(x + y).animate({backgroundColor: "#30ad03"});
}
function straightforward(p, t) {
var i = 0, j = 0, k = 0;
var boxWidth = $('#text_array .panel').outerWidth(true);
while (j < t.length && k < p.length) {
if (t[j]==p[k]) {
//turn text green
turnGreen('#t', j);
//turn pattern green
turnGreen('#p', k);
//update counters to compare next characters in the pattern and text
j = j + 1;
k = k + 1;
} else {
//turn the unmatched pattern character red
turnRed('#p', k);
turnRed('#t', j);
//turn all pattern white
for (var m = 0; m < p.length; m++) {
turnWhite('#p', m);
}
//turn all text white
for (var m = 0; m < t.length; m++) {
turnWhite('#t', m);
}
//update countes to compare the next character of text with first character of pattern
i = i + 1;
j = i;
k = 0;
//move pattern on a mismatch
animatePattern(boxWidth, i);
}
}
}
jsfiddle这里可以看到运行的动画
最佳答案
您可以使用 $.fx.speeds._default = 750;
来减慢动画速度,但您现在所做的似乎是最初对所有动画进行排队,因此它们正在播放同步。您需要做的是使用 setTimeout
或 setInterval
并创建一个“tick”函数,该函数每 x
秒运行一次以更新元素。
一些示例代码:
var intervalms = 1000
var i = 0;
function tick() {
if (!(i < 10)) return;
console.log(i++);
setTimeout(tick, intervalms)
}
tick();
或者使用间隔
var intervalms = 1000
var i = 0;
function tick() {
if (!(i < 10)) {
clearInterval(tickInterval);
return;
}
console.log(i++);
}
var tickInterval = setInterval(tick, intervalms);
关于javascript - 使用 JQuery .animate 为模式匹配算法设置动画时遇到问题。某些动画播放速度太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42742845/