在网站页面右下角添加一个“回到顶部”的按钮

HTML/CSS/JS wes 1 month ago (2026-03-12) 99 views

在网站页面右下角添加一个“回到顶部”的按钮,手机和电脑通用,通过CSS加JavaScript即可实现,代码如下:

css/js

#backToTop {   position: fixed !important;   right: 20px !important;   bottom: 25px !important;   width: 42px !important;   height: 42px !important;   line-height: 42px !important;   font-size: 18px !important;   background: #222 !important;   color: #fff !important;   border-radius: 50% !important;   text-align: center !important;   cursor: pointer !important;   z-index: 99999 !important;   opacity: 0 !important;   visibility: hidden !important;   transition: all 0.3s ease !important; } #backToTop.show {   opacity: 1 !important;   visibility: visible !important; } #backToTop:hover {   background: #007cba !important; } <div id="backToTop">↑</div> <script> const backToTopBtn = document.getElementById('backToTop'); window.addEventListener('scroll', function(){     if (window.scrollY > 150) {         backToTopBtn.classList.add('show');     } else {         backToTopBtn.classList.remove('show');     } }); backToTopBtn.addEventListener('click', function(){     window.scrollTo({top:0,behavior:'smooth'}); }); </script>