當(dāng)用戶瀏覽的網(wǎng)頁過于長的時(shí)候立由,用戶在瀏覽到網(wǎng)頁底部想要在返回頂部需要滾動好幾次滾輪才能返回頂部轧钓,不僅麻煩司致,而且用戶體驗(yàn)也會很差。現(xiàn)在的大多是頁面都會在頁面頂部或者是頁面的可見區(qū)域的某一位置固定一個(gè)按鈕聋迎,點(diǎn)擊它可以使頁面返回頂部脂矫,用戶再也不用滾動滾輪了。下面我給大家講解一下:
html樣式
<div class="gotop">返回頂部</div>
css樣式
.gotop {
width: 65px;
height: 65px;
background-color: pink;
border-radius: 50%;
position: fixed;
bottom: 100px;
right: 60px;
font-size: 15px;
line-height: 50px;
text-align: center;
display: none;
}
.active {
display: block!important;
}
js樣式
var gotop = document.getElementsByClassName("gotop")[0];//獲取那個(gè)點(diǎn)擊盒子
window.onscroll = function () { //window的滾動事件
var scroll_Height = document.documentElement.clientHeight || document.body.clientHeight;//可視區(qū)高度
var scroll_Top = document.documentElement.scrollTop || document.body.scrollTop;//滾動條距離父級頂部距離
if (scroll_Top > scroll_Height) {//判斷如果滾動條距離父級頂部距離大于可視區(qū)高度
gotop.classList.add("active")//顯示active樣式
}else{
gotop.classList.remove("active")//否則不顯示 隱藏
}
}
gotop.onclick=function(){//返回頂部盒子的點(diǎn)擊事件
document.documentElement.scrollTop=0;//滾動條距離父級頂部距離為0霉晕,就是返回頂部
document.body.scrollTop=0;//兼容
}
將這個(gè)代碼運(yùn)用到之前拍的死版中庭再,看一下效果,
這個(gè)是一屏的頁面
當(dāng)我們劃出一屏的時(shí)候出現(xiàn)滾動條牺堰,同時(shí)出現(xiàn)那個(gè)返回頂部的盒子