我有以下 HTML
<button id="btn" type="button">Click Me!</button>
<div id="outside">
<div id='inside" class="animated">
</div>
</div>
当我单击按钮时,我首先显示外部
,然后为内部
设置动画。效果很好。
当我再次单击时,我首先将内部
动画化,然后隐藏外部
。为此,我向inside
div 添加了一个事件监听器,以监听animationend
。第一次效果很好。但是,第二次我尝试隐藏外部
时,监听器被启动并且无法正常工作。现在,我试图在事件监听器第一次启动后立即将其删除,但我无法使其工作。
这是我的最后一次尝试。
...
hideOutside: =>
@inside.addEventListener 'animationend', @handler(event), no
handler: (e) =>
@sheet.removeEventListener @animationEvent, @handler(event), no
@outside.classList.remove('is-active')
我有seen sample on SO similar to mine我不明白我的有什么问题。
谢谢(请不要删除它)。
最佳答案
这个:
@inside.addEventListener 'animationend', @handler(event), no
# ---------------------------------------^^^^^^^^^^^^^^^
并没有像你想象的那样做。这实际上是在调用 @handler
,而不是传递对其的引用,因此它与以下内容相同:
x = @handler(event)
@inside.addEventListener 'animationend', x, no
因此 @handler(event)
在 addEventListener
之前被调用。
您想要使用函数引用,所以:
@inside.addEventListener 'animationend', @handler, no
和:
@sheet.removeEventListener @animationEvent, @handler, no
关于javascript - 启动后删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805214/