HTML-CSS页面返回顶部、回到底部按钮无法同时显示问题求助
问题原因
- 重复给
window.onscroll赋值:JS 中对同一个事件属性多次赋值时,后写的内容会直接覆盖先写的内容,你的第二个滚动事件逻辑直接覆盖了第一个,只有回到底部按钮的滚动逻辑会被触发。 - 变量、函数重名冲突:两个脚本块中都定义了名为
mybutton的变量和名为scrollFunction的函数,后定义的内容会覆盖先定义的,运行时永远只会操作回到底部按钮这一个元素。 - 语法错误:
bottomFunction中使用了#做注释,JS 单行注释规则为//,多余的#会触发语法报错。
修复后的完整代码
<!DOCTYPE html> <html> <head> ... <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> ... <style> /* 回到顶部按钮样式 */ #myBtn { display: none; position: fixed; bottom: 120px; left: 3.7px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: #4E2F8E; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } #myBtn:hover { background-color: #CABCE5; color:#17043A; } /* 回到底部按钮样式 */ #myBtn2 { display: none; position: fixed; bottom: 6px; left: 3.7px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: #4E2F8E; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } #myBtn2:hover { background-color: #CABCE5; color:#17043A; } </style> </head> <body> ... <!-- 功能按钮 --> <button onclick="topFunction()" id="myBtn" title="回到顶部"><i class="fa fa-arrow-circle-up"></i></button> <button onclick="bottomFunction()" id="myBtn2" title="回到底部"><i class="fa fa-arrow-circle-down"></i></button> ... <script> // 获取两个按钮元素 const topBtn = document.getElementById("myBtn"); const bottomBtn = document.getElementById("myBtn2"); // 统一绑定滚动事件 window.onscroll = function() {scrollFunction()}; function scrollFunction() { const scrollTop = document.body.scrollTop || document.documentElement.scrollTop; // 页面不在顶部时显示回到顶部按钮 if (scrollTop > 0) { topBtn.style.display = "block"; } else { topBtn.style.display = "none"; } // 页面没到最底部时显示回到底部按钮(可按自己需求修改逻辑) const scrollHeight = document.body.scrollHeight || document.documentElement.scrollHeight; const clientHeight = window.innerHeight; if (scrollTop + clientHeight < scrollHeight - 10) { // 留10px阈值避免判断误差 bottomBtn.style.display = "block"; } else { bottomBtn.style.display = "none"; } } // 回到顶部逻辑 function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } // 回到底部逻辑 function bottomFunction() { window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); } </script> </body> </html>
补充说明
你原代码中图标用的far类是Font Awesome 5+版本的属性,你引入的4.7版本仅支持fa开头的类,已同步修改图标类名,避免图标不显示的问题。如果你需要保持原来的图标样式,升级Font Awesome版本即可。
内容的提问来源于stack exchange,提问作者tedioustortoise
相关产品推荐
相关产品推荐

