我有一个推送菜单,它有一个动画渐变,但我只想在菜单打开时进行动画/播放,显然是出于性能原因。
我的渐变插件代码如下:
// Animated Gradient
var colors = new Array(
[62,35,255],
[60,255,60],
[255,35,98],
[45,175,230],
[255,0,255],
[255,128,0]);
var step = 0;
var colorIndices = [0,1,2,3];
var gradientSpeed = 0.001;
function updateGradient()
{
if ( $===undefined ) return;
var c0_0 = colors[colorIndices[0]];
var c0_1 = colors[colorIndices[1]];
var c1_0 = colors[colorIndices[2]];
var c1_1 = colors[colorIndices[3]];
var istep = 1 - step;
var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
var color1 = "rgb("+r1+","+g1+","+b1+")";
var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
var color2 = "rgb("+r2+","+g2+","+b2+")";
$('#primary-menu').css({
background: "-webkit-gradient(linear, left top, right bottom, from("+color1+"), to("+color2+"))"}).css({
background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});
step += gradientSpeed;
if ( step >= 1 )
{
step %= 1;
colorIndices[0] = colorIndices[1];
colorIndices[2] = colorIndices[3];
colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
}
}
当我打开菜单时,我设法只播放动画渐变,但是当我关闭菜单时我无法停止它,我该怎么做?:
showmenu.onclick = function() {
if ($('nav').hasClass('visible')) {
// Opened menu code here
} else {
// Closed menu code here
// Initialise plugin when menu is open
setInterval(updateGradient,10);
}
};
答案 0 :(得分:1)
您需要clearInterval()
而不是仅仅调用setInterval()
将其分配给变量。 setInterval()
和setTimeout()
都会返回一个标识符,以便稍后停止
// in scope available to all your handler code
var timer;
// in initialization
timer = setInterval(updateGradient,10);
// in handler where you want to stop it
clearInterval(timer);
答案 1 :(得分:0)
你试过这个吗?
if ( $('nav').is(':visible') ) { ... }