滚动到顶部,动画为百分比

Scroll to Top with Animate as Percent

本文关键字:百分比 动画 顶部 滚动      更新时间:2023-09-26

我最近尝试使用animate jquery将滚动到顶部。一切似乎都很好。但我需要像百分比一样做。例如 scrollTop 100%那么它滚动 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%),然后使用该像素数。

正如您所说,滚动顶部高度以像素为单位。从文档中:

一个整数,指示要将滚动条设置为的新位置。

您必须自己计算百分比:

$('#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");
    });
});