var topBtn = document.getElementById('top');
// 獲取視窗高度
var winHeight = document.documentElement.clientHeight;
window.onscroll = function () {
// 獲取頁面向上滾動距離,chrome瀏覽器識別document.body.scrollTop,而火狐識別document.documentElement.scrollTop,這里做了兼容處理
var toTop = document.documentElement.scrollTop || document.body.scrollTop;
// 如果滾動超過一屏,返回頂部按鈕出現,反之隱藏
if(toTop>=winHeight){
topBtn.style.display = 'block';
}else {
topBtn.style.display = 'none';
}
}
topBtn.onclick=function () {
var timer = setInterval(function () {
var toTop = document.documentElement.scrollTop || document.body.scrollTop;
// 判斷是否到達頂部,到達頂部停止滾動,沒到達頂部繼續滾動
if(toTop == 0){
clearInterval(timer);
}else {
// 設置滾動速度
var speed = Math.ceil(toTop/5);
// 頁面向上滾動
document.documentElement.scrollTop=document.body.scrollTop=toTop-speed;
}
},50);
}
大家介紹如何通過 JS/CSS 實現網頁返回頂部效果。
CSS 按鈕樣式:
#myBtn {
display: none; /* 默認隱藏 */
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: red; /* 設置背景顏色,你可以設置自己想要的顏色或圖片 */
color: white; /* 文本顏色 */
cursor: pointer;
padding: 15px;
border-radius: 10px; /* 圓角 */
}
*請認真填寫需求信息,我們會在24小時內與您取得聯系。