我有一个大约10秒完成的函数,如果在第一次迭代完成之前重新激活就会中断它 - 它充当文本推子 - JQuery不是我想要使用纯JS的选项
我的功能:
//Text fading effect
function fadeText() {
var hex1 = 153,
hex2 = 204,
hex3 = 51;
function innerFade() {
if (hex1 >= 30) {
hex1 -= 1;
document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
}
if (hex2 >= 30) {
hex2 -= 1;
document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
}
if (hex3 >= 30) {
hex3 -= 1;
document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
}
setTimeout(innerFade, 20);
}
innerFade();
}
这是在按下按钮时激活的,如果在动画完成之前再次激活,我希望第一次迭代取消或设置文本已分配给innerHTML
的div的innerHTML="";
答案 0 :(得分:1)
大编辑:
//Set colour function
function setColor(elementName, r, g, b) {
document.getElementById(elementName).style.color = "rgb(" + r + "," + g + "," + b + ")";
}
//Text fading effect
var animationActive = false;
function fadeText() {
if (animationActive) return;
animationActive = true;
var hex1 = 153,
hex2 = 204,
hex3 = 51;
function innerFade() {
var rDone, gDone, bDone;
if (hex1 >= 30) {
hex1 -= 1;
setColor('confirmation', hex1, hex2, hex3);
} else {rDone = true;}
if (hex2 >= 30) {
hex2 -= 1;
setColor('confirmation', hex1, hex2, hex3);
} else {gDone = true;}
if (hex3 >= 30) {
hex3 -= 1;
setColor('confirmation', hex1, hex2, hex3);
} else {bDone = true;}
if (rDone && gDone && bDone) {
animationActive = false;
}
}
setTimeout(innerFade, 20);
}
答案 1 :(得分:0)
您可以禁用该按钮以防止再次调用该函数:
HTML:
<button onclick="fadeText(this)"> Fade text </button>
JavaScript:
function fadeText(btn) {
var elm = document.getElementById('confirmation'),
c = [153, 204, 51];
function loop() {
for (var i = 0; i < c.length; i++) {
if (c[i] >= 30) c[i] -= 1;
}
elm.style.color = 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] + ')';
return c[0] < 30 && c[1] < 30 && c[2] < 30 ?
btn.disabled = false : setTimeout(loop, 20);
}
btn.disabled = true;
loop();
}