1、网站返回网页顶部代码
<!-- Back To Top Button -->
<button id="backToTop" aria-label="Back to top">
↑
</button>
<style>
#backToTop {
position: fixed;
right: 28px;
bottom: 90px;
width: 46px;
height: 46px;
border: 2px solid #ff4b2b;
background: #164782;
color: #ffffff;
font-size: 26px;
font-weight: bold;
line-height: 1;
border-radius: 4px;
cursor: pointer;
z-index: 9999;
display: none;
align-items: center;
justify-content: center;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.18);
transition: all 0.3s ease;
}
#backToTop:hover {
background: #ff4b2b;
color: #ffffff;
transform: translateY(-3px);
}
#backToTop.show {
display: flex;
}
@media (max-width: 768px) {
#backToTop {
right: 18px;
bottom: 70px;
width: 42px;
height: 42px;
font-size: 24px;
}
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
const backToTop = document.getElementById("backToTop");
window.addEventListener("scroll", function () {
if (window.scrollY > 300) {
backToTop.classList.add("show");
} else {
backToTop.classList.remove("show");
}
});
backToTop.addEventListener("click", function () {
window.scrollTo({
top: 0,
behavior: "smooth"
});
});
});
</script>

乐予博客

