为什么我的悬停功能可以工作,但我的 onmouseleave 功能却不能?(在控制台调用该函数有效)

这是我的代码笔:

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

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

我有 UIController.showMenu 和 UIController.closeMenu。

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

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

如果我向函数添加 console.log("Hello") ,它将在页面首次加载时触发。但当我需要它时就不起作用了。

应用程序.js:

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();

})

导航栏.css:


.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%;

}


浮云间
浏览 44回答 2
2回答

叮当猫咪

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

慕森王

添加事件时不应使用“on”,只需使用函数名称document.querySelector('#sideMenu').addEventListener("mouseleave", UIController.closeMenu);代替document.querySelector('#sideMenu').addEventListener("onmouseleave", UIController.closeMenu);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5