Javascript事件监听器未启动

Javascript eventListeners not firing

本文关键字:启动 监听器 事件 Javascript      更新时间:2023-09-26

我正试图让所有按钮在点击时都像第一个按钮一样做同样的事情。基本上,它只是在点击时调用一个函数。

该函数更改目标div的innerHtml,添加一个Css动画类,然后在mouseout上删除Css动画。

这正是我希望它在第一个按钮上的工作方式,但不是在第二个和最后一个按钮上。

function declaration() {
    document.getElementById("me").innerHTML = "I am a function declaration and i                
    hoist to the top of the code, you
    can call me before i get
    declared.I look like this: < br > function declaration() {}
    ";
    document.getElementById("me")
        .classList.add("slideIt");
    document.getElementById("fnDeclaration")
        .addEventListener('mouseout', function() {
            document.getElementById("me")
                .classList.remove("slideIt");
        });
}
document.getElementById("fnDeclaration").addEventListener("click", function() {
    declaration();
});

http://codepen.io/damianocel/pen/xwJmwN

为什么(没有)发生这种事?

您的内容div(#me)在HTML中最后设置(因此在DOM中),因此向下滑动时它位于按钮的顶部。

因此,实际上,只要向下滑动动画开始,就可以从按钮中mouseout,根据您的代码,这将删除slideIt类,从而停止动画。

一个快速的解决方案可以简单地将您的内容div向下推到按钮下方(z索引方向):#me {z-index: -10;}

演示:http://codepen.io/anon/pen/vNvqYx