当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue项目tween方法实现返回顶部的示例代码

vue项目tween方法实现返回顶部的示例代码

2018年03月12日  | 移动技术网IT编程  | 我要评论

夜半一点钟,鳝始鳝终是什么意思,热火直播

一、场景

tween.js是一款可生成平滑动画效果的js动画库

当你要实现一个返回顶部的功能时候你会怎么做,大部分人会使用document.body.scrolltop =0;这么写就实现了功能,

不过要更加的细腻一点我们不妨用tween的缓动来实现,看看效果如何吧。

之前我们写过tween的相关文章,这里不做介绍了。

二、代码

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <style type="text/css">
      #app{width: 100%; height: 3000px;background: #cccccc;}
      .backtop{
        width: 1.5rem;
        height: 1.5rem;
        border: 1px solid #ff0000;
        position: fixed;
        right: 1rem;
        bottom: 2rem;
        border-radius: 50%;
        /*background: url(/static/imgs/backtop20180226.png) no-repeat 40%;*/
        background-size: 70% 100%;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div @click="backtop()" class="backtop">top</div>
    </div>
    
    <script type="text/javascript">
      var app = new vue({
        el:"#app",
        data:{
          
        },
        methods:{
          backtop(){
//             * t: current time(当前时间);
//             * b: beginning value(初始值);
//             * c: change in value(变化量);
//             * d: duration(持续时间)。
            var tween = {
              linear: function(t, b, c, d) { //匀速运动,想要实现其他的效果可以使用tween的其他方法
                return c * t / d + b; 
              }
            }
            math.tween = tween;
            var t = 1;
            const b = document.documentelement.scrolltop;
            const c = 50;
            const d = 5;
            const setint = setinterval(()=>{
              t--;
              console.log(t)
              if(document.documentelement.scrolltop == 0){clearinterval(setint)}
              console.log(t);
              const backtop = tween.linear(t,b,c,d);
               console.log(backtop);
              document.documentelement.scrolltop = backtop;
            },20)
          }
        }
      })
    </script>
  </body>
</html>

三、requestanimationframe改写setinterval方法:

methods:{
      backtop(){
        var tween = {
          linear: function(t, b, c, d) { //匀速
            return c * t / d + b; 
          }
        }
        math.tween = tween;
        var t = 1;
        const b = document.body.scrolltop;
        const c = 1;
        const d = 1;
        var timer;
        timer= requestanimationframe(function fn(){
          if(document.body.scrolltop > 0){
            t--;
            console.log(t)
            console.log(t);
            const backtop = tween.linear(t,b,c,d);
             console.log(backtop);
            document.body.scrolltop = backtop;
            timer = requestanimationframe(fn);
          }else{
            cancelanimationframe(timer)
          }
        })
      }
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网