簡體   English   中英

滾動到頂部,Animate為百分比

[英]Scroll to Top with Animate as Percent

我最近嘗試使用animate jquery使滾動到頂部。 一切似乎都好。 但我需要像百分比那樣做。 例如, scrollTop100%然后滾動為100%。 我不確定。 現在我相信它是像素。 如何在jquery的動畫函數中使用百分比,類似於scrollTop:100%我試過但我得到控制台錯誤。

這是小提琴

 $('#spnTop').on("click",function(){
    $('html,body').animate({ scrollTop: 0 }, 'slow', function () {
                          alert("reached top");
                        });
    }); 

因為,正如您所發現的, animate需要像素值,您必須獲取元素的高度( innerHeight可能是最好的),將百分比應用於它( Math.round(height * percentage / 100)假設percentage值像70表示70%),然后使用那個像素數。

如你所說,scrollTop高度以像素為單位。 來自文檔

一個整數,指示將滾動條設置為的新位置。

您必須自己計算百分比:

$('#spnTop').on("click",function(){
    var percentageToScroll = 0.50;
    var documentHeight = $(document).height();
    var scrollAmount = Math.floor(documentHeight * percentageToScroll);
    $('html,body').animate({ scrollTop: scrollAmount }, 'slow', function () {
                          alert("reached top");
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM