简体   繁体   English

CSS animationend EventListener反复触发

[英]CSS animationend EventListener Firing Repeatedly

I am trying to simulate a collision detection by firing an event if all of the following conditions are present: 如果满足以下所有条件,我将尝试通过触发事件来模拟碰撞检测:

  1. Up arrow key is down 向上箭头键向下
  2. The jump animation (assigned with cycleUp class) has ended 跳转动画(由cycleUp类分配)已结束
  3. The user has left scrolled past a certain amount of pixels 用户向左滚动超过一定数量的像素

The issue is that the eventListener is rapidly firing. 问题是eventListener正在迅速触发。 I tried using a debounce function, but it only delayed the rapid fire. 我尝试使用防抖动功能,但它只会延迟快速开火。

Javascript/Jquery 使用Javascript / jQuery的

$(document).keydown(function(e) {
                if (e.which == '39') {
                    $('#mainSprite').attr("class","cycleR");
                }   
                else if (e.which == '37'){
                    $('#mainSprite').attr("class","cycleL");
                }
                else if (e.which == '38'){
                    $('#mainSprite').attr("class","cycleUp");

                    document.getElementById("mainSprite").addEventListener("animationend", function(){

                        var pos = $(document).scrollLeft();

                        if( pos >= 25 ){
                                alert("Jump");
                            }

                    }, false);

                }

                else {
                    $('#mainSprite').removeClass("cycleR");
                }
            });


$(this).keyup(function(){
        $('#mainSprite').removeClass();
});

Here is a link to the site where I am trying to implement the code. 这是我尝试实现代码的站点的链接。 The little character will hop up and "hit" a marker to trigger an event. 小人物会跳起来并“打”一个标记以触发事件。 Please note, user will need to be able to scroll to multiple locations down the page and still have the event listener fire (aka "collide" with multiple objects).It essentially works like GPS. 请注意,用户将需要能够向下滚动到页面的多个位置,并且仍使事件监听器触发(也就是与多个对象“碰撞”)。它的工作原理与GPS类似。 If the user has scrolled to the x-coordinate, and the animation has placed the character at the y-coordinate, fire an event. 如果用户已滚动到x坐标,并且动画已将角色放置在y坐标,则触发事件。

On every keydown where e.which == 38 , you are adding yet another event listener for animationend . e.which == 38每个keydown上,您都将为animationend添加另一个事件侦听器。 That means after a few keys, you will have multiple listeners and thus your callback will be called multiple times. 这意味着在几个键之后,您将拥有多个侦听器,因此您的回调将被多次调用。

You have to either add the eventListener only once ever or you have to remove the event listener after it fires. 您必须只添加一次eventListener,或者在事件触发后将其删除。

If using jQuery, you can use the .one() method of installing the event handler so that it will be automatically removed after it fires. 如果使用jQuery,则可以使用.one()方法安装事件处理程序,以便在触发事件后将其自动删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM