聚合物:添加和删除 class(1 秒后)

Polymer: Add and remove class (after 1 second)

我在 Polymer 模板中有一个 <div>,我想使用 CSS 对其进行动画处理。我希望能够在每次调用特定观察者函数 (onTriggered) 时重新触发动画。

我尝试了以下函数来添加然后删除 CSS class 以便在再次调用观察者时可以重新触发它,但是它 returns Cannot read property 'myContainer' of undefined。我知道这是由于无法在 Javascript 函数中调用 Polymer 对象,但我找不到替代解决方案。

onTriggered: function (newData, oldData) {
    if (oldData && oldData !== newData) {
        this.$.myContainer.classList.add("animated", "jello");
        setTimeout(function() {
            this.$.myContainer.classList.remove("animated", "jello");
        }, 1000);
    }
}

在 Polymer 元素中同步添加然后(在 x 秒后)删除 CSS class 的最佳方法是什么?

这是因为您的 setTimeout 回调函数中的范围发生了变化。您需要更改范围以在回调中使用 this

请尝试:

setTimeout(function() {
   this.$.myContainer.classList.remove("animated", "jello");
}, 1000, this);

或者这个:

setTimeout(function() {
   this.$.myContainer.classList.remove("animated", "jello");
}.bind(this), 1000);

正如@Kejt 所说,范围确实是问题所在。为了解决这个问题,我不得不将 this 赋值给一个变量,然后在 setTimeout 函数中引用该变量,即:

this.$.myContainer.classList.add("animated", "jello");
var polymerThis = this;
setTimeout(function() {
   polymerThis.$.myContainer.classList.remove("animated", "jello");
}, 1000);