过渡结束事件未触发

时间:2016-02-02 09:05:07

标签: javascript css events css-transitions transition

我正在编写Polymer web组件,我想在其中设置元素的动画。为此,我做了以下功能:

_animateRipple: function(x, y, color, amplitude) {
    var ripple = this.$.ripple;

    // Transition end listener
    ripple.addEventListener(this._whichTransitionEvent, transitionEndListener);

    // Ripple ended
    var transitionEndListener = function() {
        console.log("RIPPLE ENDED");
        ripple.classList.remove("transition-on");
        ripple.removeEventListener(this._whichTransitionEvent, transitionEndListener);
    }

    // Initial styling
    ripple.style.top = y + "px";
    ripple.style.left = x + "px";
    ripple.style.height = ripple.style.width = "0";
    ripple.style.backgroundColor = color;

    // Trigger ripple
    setTimeout(function() {
        ripple.classList.add("transition-on");
        ripple.style.height = ripple.style.width = amplitude + "px";
        ripple.style.top = y - (amplitude / 2) + "px";
        ripple.style.left = x - (amplitude / 2) + "px";
    }, 20);
}

this._whichTransitionEvent只是一个具有当前平台的正确事件名称的变量,它工作正常,这不是问题。

显然.transition-on CSS类添加了转换,它可以正常工作。

我希望transitionEndListener在转换结束时触发(这样" RIPPLE ENDED"显示在控制台中),但它没有触发。

有什么想法吗?我尝试了很多东西......

1 个答案:

答案 0 :(得分:0)

问题是,在添加时,listener变量是未定义的,因此解决方案是在附加事件侦听器之前声明它。

_animateRipple: function(x, y, color, amplitude) {
    var ripple = this.$.ripple;

    // Ripple ended
    var transitionEndListener = function() {
        console.log("RIPPLE ENDED");
        ripple.classList.remove("transition-on");
        ripple.removeEventListener(this._whichTransitionEvent, transitionEndListener);
    }

    // Transition end listener
    ripple.addEventListener(this._whichTransitionEvent, transitionEndListener);

    // Initial styling
    ripple.style.top = y + "px";
    ripple.style.left = x + "px";
    ripple.style.height = ripple.style.width = "0";
    ripple.style.backgroundColor = color;

    // Trigger ripple
    setTimeout(function() {
        ripple.classList.add("transition-on");
        ripple.style.height = ripple.style.width = amplitude + "px";
        ripple.style.top = y - (amplitude / 2) + "px";
        ripple.style.left = x - (amplitude / 2) + "px";
    }, 20);
}