动画结束侦听器无法正常工作

时间:2015-02-03 16:50:51

标签: javascript css animation event-listener

我的时间栏中有一个带有CSS的动画id="progress-bar"和动画类.anim。 动画是CSS:

@-webkit-keyframes myfirst {
  from {
    width: 100%;
    background-color: #86e01e;
  }
  to {
    width: 0%;
    background-color: #f63a0f;
  }
}

.anim {
-webkit-animation: myfirst 5s linear;
-webkit-animation-fill-mode: forwards;
}

我正在使用函数reset()

重新启动动画
function reset() {
document.getElementById("progress-bar").className = "";
setTimeout(function(){document.getElementById("progress-bar").className = "anim";},1);
}

现在我希望在动画结束时执行函数lose()。 我也尝试过动画和听众的多项内容,但它对我不起作用......

var x = document.getElementById("progress-bar");
x.addEventListener('webkitAnimationEnd', function() { 
lose(); //whatever i type here doesn't work
}, false);

有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

尝试将此作为修复:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var color = ["Red", "Pink", "SkyBlue", "Grey", "Purple", "Orange"]; 

ctx.fillStyle = color [Math.floor(Math.random() * color.length)];

var posicion = 0;
var tamano = 0;
var clicks= 0;    

setInterval(function () {
    ctx.clearRect(0, 0, 400, 400);
    
    // this was added
    var tamanoWidth;
    if((tamano + posicion) < 400) tamanoWidth = tamano;
    else tamanoWidth = 400 - posicion;
    
    ctx.fillRect(posicion, 0, tamanoWidth, 400-tamano);
    
    // output to div
    $("#dimensions").html("Width: " + tamanoWidth + "<br/>Height: " + (400-tamano));
    
    posicion++;
    tamano++;
    if (posicion > 400){
        posicion = 0;
        tamano = 0;
    }
}, 30);

$("canvas").click(function(){
    ctx.fillStyle=color [Math.floor(Math.random() * color.length)];
    });