JS让页面滚动到顶部和底部

滚动到顶部,Class名为go-top的点击事件:

jQuery('.go-top').on('click', function (e) {
    e.preventDefault();
    jQuery('html, body').animate({ scrollTop: 0 }, duration);
    return false;
})

滚动到底部,Class名为go-bottom的点击事件:

jQuery('.go-bottom').on('click', function (e) {
    var t = document.body.clientHeight;
    window.scroll({ top: t, left: 0, behavior: 'smooth' });
})

我们发现上们滚动到底部代码虽简单,但没有滚动动画,于是我们优化一下

jQuery('.go-bottom').on('click', function (e) {
    (function smoothscroll() {
        const currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // 已经被卷掉的高度
        const clientHeight = document.documentElement.clientHeight; // 浏览器高度
        const scrollHeight = document.documentElement.scrollHeight; // 总高度
        if (scrollHeight - 10 > currentScroll + clientHeight) {
            window.requestAnimationFrame(smoothscroll);
            window.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);
        }
    })();
})

参考资料:

SegmentFault 思否 – js实现滚动条滑动到底部

本文采用 CC BY-NC-SA 3.0 Unported 许可,转载请以超链接注明出处。
原文地址:JS让页面滚动到顶部和底部 作者:松鼠小
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
Source: Telegram @AmashiroNatsukiEars_NoWord Sticker
Source: Github @zhheo/Sticker-Heo
Source: github.com/k4yt3x/flowerhd
颜文字
AmashiroNatsukiEars
Heo
小恐龙
花!
上一篇
下一篇