onmouseenter事件未触发 回到顶部按钮显隐异常排查
onmouseenter函数未正常触发- 实现回到顶部按钮需求:页面到达顶部时将按钮
display设为none隐藏,尝试classList操作类名、直接修改style.display两种方案均未生效 - 预期逻辑:触发
onmouseleave事件时按钮重新显示,已编写对应处理函数
JavaScript
const topDiv = document.getElementById('topDiv') const arrowup = document.getElementById('arrowup') const hideArrow = () => { if (topDiv) { arrowup.classList.remove(showme'); arrowup.classlist.add('hideme'); } else { arrowup.classList.add('showme'); } } const showArrow = () => { if (!topDiv) { arrowup.classList.remove('hideme'); arrowup.classList.add('showme'); } }
CSS
#top { height: 1000px; } a { position: fixed; top: 10px; } .showme { display: block; } .hideme { display: none; }
HTML
<div onmouseleave="showArrow() onmouseenter="hideArrow()" id="top"> hello </div> <a class="showme" id="arrowup" onClick="hideArrow()" href="#top"> click me </a>
代码存在多处语法错误、逻辑错误,直接导致功能失效,逐一修复即可:
HTML事件属性语法错误(onmouseenter不触发的核心原因)
顶部div的onmouseleave属性值缺少闭合双引号,浏览器解析时会把后续的onmouseenter直接当成onmouseleave属性值的一部分,两个事件都没有完成绑定。
修复:补全属性引号,改为<div onmouseleave="showArrow()" onmouseenter="hideArrow()" id="top">DOM获取ID不匹配
JS中获取顶部元素时写的ID是topDiv,但HTML中对应元素的实际ID是top,导致topDiv变量始终为null,后续所有判断逻辑完全失效。
修复:将获取元素代码改为const topDiv = document.getElementById('top')JS语法拼写错误
classList.remove(showme')缺少字符串前引号,属于语法错误,会直接中断JS执行classlist.add('hideme')中API名拼写错误,正确写法是驼峰命名的classList,全小写会报undefined错误
修复:修正为arrowup.classList.remove('showme')、arrowup.classList.add('hideme')
判断逻辑冗余错误
现有逻辑判断topDiv是否存在,但DOM正常加载完成后该元素是固定存在的,这个判断和“鼠标是否在顶部区域”“页面是否滚动到顶部”没有任何关系。既然已经把hideArrow绑定到鼠标进入顶部区域的事件、showArrow绑定到鼠标离开顶部区域的事件,触发事件时直接执行类名切换即可,不需要额外加判断。
简化后的函数逻辑:const hideArrow = () => { arrowup.classList.remove('showme'); arrowup.classList.add('hideme'); } const showArrow = () => { arrowup.classList.remove('hideme'); arrowup.classList.add('showme'); }点击事件逻辑冲突
回到顶部按钮绑定的onClick="hideArrow()"会导致点击按钮时立刻隐藏按钮,不符合“回到顶部后再隐藏”的预期,直接移除该点击事件绑定即可,锚点本身会完成回到顶部的行为。
补充:如果要实现“页面滚动到顶部时自动隐藏,向下滚动时自动显示”的通用回到顶部按钮逻辑,不要用鼠标进入/离开事件,应该监听页面
scroll事件,判断window.scrollY === 0时隐藏按钮,否则显示,适配所有滚动场景。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> #top { height: 1000px; } a { position: fixed; top: 10px; } .showme { display: block; } .hideme { display: none; } </style> </head> <body> <div onmouseleave="showArrow()" onmouseenter="hideArrow()" id="top"> hello </div> <a class="showme" id="arrowup" href="#top"> 回到顶部 </a> <script> const topDiv = document.getElementById('top') const arrowup = document.getElementById('arrowup') const hideArrow = () => { arrowup.classList.remove('showme'); arrowup.classList.add('hideme'); } const showArrow = () => { arrowup.classList.remove('hideme'); arrowup.classList.add('showme'); } </script> </body> </html>
内容的提问来源于stack exchange,提问作者someone

