页面置顶效果通常是指在网页滚动到一定位置时,显示一个固定在页面顶部的元素,以便用户可以随时点击返回页面顶部。这种效果在很多网站中都有应用,尤其是在内容较多的页面中。
<button id="back-to-top" title="Go to top">Top</button>
#back-to-top {
display: none; /* 默认隐藏 */
position: fixed; /* 固定定位 */
bottom: 20px; /* 距离底部的距离 */
right: 30px; /* 距离右侧的距离 */
z-index: 99; /* 确保在最上层 */
font-size: 18px;
border: none;
outline: none;
background-color: #555;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#back-to-top:hover {
background-color: #777;
}
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("back-to-top").style.display = "block";
} else {
document.getElementById("back-to-top").style.display = "none";
}
}
document.getElementById("back-to-top").onclick = function() {
scrollToTop(800); // 800毫秒内滚动到顶部
};
function scrollToTop(scrollDuration) {
var scrollStep = -window.scrollY / (scrollDuration / 15),
scrollInterval = setInterval(function(){
if ( window.scrollY !== 0 ) {
window.scrollBy( 0, scrollStep );
} else {
clearInterval(scrollInterval);
}
},15);
}
通过以上步骤和优化,可以实现一个高效且用户体验良好的页面置顶效果。
领取专属 10元无门槛券
手把手带您无忧上云