前端 平滑滚动到底部/顶部

页面滚动时,添加平滑特效

1.在页面入口处,添加css

1 html {

2    scroll-behavior: smooth;

3 }

添加全局css之后,直接使用window.scroll(0,0)就可以平滑滚动到顶部了。

注:兼容性很差,仅支持火狐、chrome高级版本

2.指定滚动操作,使用平滑效果

平滑滚动到某块元素的底部:scrollIntoView

复制代码

1    let anchorElement = document.getElementById("softwareHeader-container");

2    let scrollIntoViewOptions: ScrollIntoViewOptions = {

3        block: 'end',

4        behavior: "smooth"

5    }

6    if (anchorElement) {

7        anchorElement.scrollIntoView(scrollIntoViewOptions)

8    }

复制代码

或者平滑滚动到指定位置:ScrollToOptions、scrollTo

复制代码

1  let scrollOptions:ScrollToOptions = {

2    left: 0,

3    top: 1000,

4    behavior:'smooth'

5  }

6

7  window.scrollTo(scrollOptions);

复制代码

兼容性:大部分支持,猎豹不支持。

3.添加JS滚动代码

滚动到顶部:

复制代码

1    returnTop = () => {

2        //记录当前执行动画的标识

3        let animationStepNumber;

4        function exeucteAnimationByStep() {

5            //当前页面的滚动高度

6            let currentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;

7            if (currentScrollTop >= 4) {

8                animationStepNumber = window.requestAnimationFrame(exeucteAnimationByStep);

9                let scrollLocationChanging = currentScrollTop / 9;

10                scrollLocationChanging = scrollLocationChanging > 1 ? scrollLocationChanging : 1;

11                let newScrollTop = currentScrollTop - scrollLocationChanging;

12                window.scrollTo(0, newScrollTop);

13            } else {

14                window.cancelAnimationFrame(animationStepNumber);

15                window.scrollTo(0, 0);

16            }

17        }

18        animationStepNumber = window.requestAnimationFrame(exeucteAnimationByStep);

19    }

复制代码

滚动到底部:

复制代码

1  scrollToPageBottom = () => {

2    let animationStepNumber;

3    function exeucteAnimationByStep() {

4      let currentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;

5      let totalHeight = (document.documentElement.scrollHeight || document.body.scrollHeight) - window.innerHeight;

6      //剩余的高度

7      let scrollingHeight = totalHeight - currentScrollTop;

8      if (scrollingHeight >= 4) {

9        animationStepNumber = window.requestAnimationFrame(exeucteAnimationByStep);

10        //滚动变量

11        let scrollChangedHeight = scrollingHeight / 9;

12        scrollChangedHeight = scrollChangedHeight > 1 ? scrollChangedHeight : 1;

13        window.scrollTo(0, currentScrollTop + scrollChangedHeight);

14      } else {

15        window.cancelAnimationFrame(animationStepNumber);

16        window.scrollTo(0, totalHeight);

17      }

18    }

19    animationStepNumber = window.requestAnimationFrame(exeucteAnimationByStep);

20  };

亚马逊测评 www.yisuping.com

你可能感兴趣的:(前端 平滑滚动到底部/顶部)