天天看點

jq實作點選按鈕回到頂部

回到頂部按鈕

重新整理後根據頁面位置修改按鈕顯示狀态

頁面滾動後,按鈕顯示狀态

點選按鈕後回到頂部動畫

js代碼

//重新整理頁面按鈕顯示狀态

//重新整理頁面後已經滾動到上面的頁面高度
var siteHeight = $('body,html').scrollTop();
//頁面高度-底部高度
var scrollHeight = $('body,html').height()-200;
//浏覽器視窗高度
var windowHeight = $(window).height();
//重新整理頁面後按鈕定位,108為基礎距離
var goTopHeight = siteHeight + windowHeight +108 -scrollHeight;
if(siteHeight < 300){
    $('.go_top').css('display','none');
}else{
    $('.go_top').css('display','block');
    //滾動到底部(臨近底部),按鈕定位
    if(siteHeight + windowHeight >= scrollHeight){
        $('.go_top').css('bottom',goTopHeight + 'px');
    }
    
}
//頁面滾動控制按鈕顯示
$(window).scroll(function () {
    //已經滾動到上面的頁面高度
   var scrollTop = $(this).scrollTop();
   //計算滾動時,按鈕據底部的距離,108為基礎距離
   var topheight = scrollTop + windowHeight - scrollHeight +108;
    //此處是滾動條到底部時候觸發的事件,在這裡寫要加載的資料,或者是拉動滾動條的操作
    if(scrollTop > 300) {
        $('.go_top').css('display','block');
        //滾動到底部(臨近底部),按鈕定位
        if (scrollTop + windowHeight >= scrollHeight) {
            $('.go_top').css('bottom',topheight+'px');
        }else{
            $('.go_top').css('bottom','108px');
        }
    }else {
        $('.go_top').css('display','none');
    }
});
//點選回到頂部動畫
$('.go_top').on('click',function(){
    $('body,html').animate({
        scrollTop:0
    },500);
    return false;
})
           

html代碼

<div class="go_top">回到頂部</div>