I recently tried to make the scroll to top with animate jquery. Everything seems ok. But I need to do as with percentage. For Example scrollTop
is 100%
then it scroll's 100% . I am not sure. Right now i believe it is in pixel. How to use percentage in animate function of jquery, something like scrollTop:100%
I tried that but i get console error.
Here is the fiddle
$('#spnTop').on("click",function(){
$('html,body').animate({ scrollTop: 0 }, 'slow', function () {
alert("reached top");
});
});
因为,正如您所发现的, animate
需要像素值,您必须获取元素的高度( innerHeight
可能是最好的),将百分比应用于它( Math.round(height * percentage / 100)
假设percentage
值像70
表示70%),然后使用那个像素数。
As you say, the scrollTop height is in pixels. From the docs :
An integer indicating the new position to set the scroll bar to.
You would have to calculate the percentage yourself:
$('#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");
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.