为什么我的悬停功能正常运行,但onmouseleave函数却无效? (在控制台中调用该功能有效)

时间:2020-04-21 14:19:39

标签: javascript html css addeventlistener onmouseout

这是我的代码笔:

https://codepen.io/squishyboots19996/pen/BaoQjPL

我正在尝试创建一个导航菜单,当您将鼠标悬停在箭头上时会滑入,然后在鼠标离开菜单时滑出。

我有UIController.showMenu和UIController.closeMenu。

如果我在控制台中调用其中任何一个,它们将按预期工作。

但是closeMenu的事件侦听器不起作用。它只是没有检测到鼠标离开菜单并且没有关闭。

如果我向该函数添加console.log(“ Hello”),则它将在页面首次加载时触发。但是当我需要它时将无法工作。

app.js:

    #include<iostream>
using namespace std;
int max(int a,int b){
   if(a>b)
       return a;
   else
       return b;
}
int main(){
   int coinrow[]={5,1,2,10,6,2};
   int size=sizeof(coinrow)/sizeof(coinrow[0]);
   //cout<<size;
   int i;
   int coins[size+1];
   for(i=0;i<size;i++){
       coins[i+1]=coinrow[i];
   }

   int F[size+1];
   F[0]=0;
   F[1]=coins[1];
   for(i=2;i<=size;i++){
       F[i]=max(coins[i]+F[i-2],F[i-1]);
   }
   cout<<F[size];
}

navbar.css:

var Controller = (function() {
    UIController.updateNav;
    setInterval(UIController.moveArrowDown, 3000);
    //UIController.addBodyMargin();
 document.querySelector('#menuArrow').addEventListener("mouseover", UIController.openMenu);
      document.querySelector('#sideMenu').addEventListener("onmouseleave", UIController.closeMenu);
});
//-----------------------------------------------------------
var UIController = (function() {

    return {
        openMenu: (function(){
          document.getElementById('sideMenu').style.marginLeft = '0';
          document.getElementById('menuArrow').style.marginLeft = '250px';
          document.body.style.marginLeft = '25px'
        }),
        closeMenu: (function(){
          document.getElementById('sideMenu').style.marginLeft = '-250px';
          document.getElementById('menuArrow').style.marginLeft = '0';
          document.body.style.marginLeft = '0';
        })
        }

})();


document.addEventListener('DOMContentLoaded', (event) => {
  Controller();
})

HTML:

.sidemenu {
  height: 100vh;
  width: 250px;
  position: fixed;
  top: 0;
  left: 0;
  background-color: red;
  z-index: 5001;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-left: -250px;
  transition: .5s;
  cursor: pointer;
}

.sidemenu ul {
  list-style: none;
  padding: 0;
}

.sidemenu a {
  text-decoration: none;
  font-size: 2rem;
}

.expand-arrow {
  z-index: 4999;
  position: fixed;
  transition: .5s;
  bottom: 50%;
}

2 个答案:

答案 0 :(得分:1)

使用addEventListener()方法时,它是"mouseleave"而不是"onmouseleave"

答案 1 :(得分:1)

添加事件时,您不应使用“ on”,而应使用 功能

document.querySelector('#sideMenu').addEventListener("mouseleave", UIController.closeMenu);

代替

document.querySelector('#sideMenu').addEventListener("onmouseleave", UIController.closeMenu);