Home > Article > Web Front-end > How to achieve return to top through tween method in vue project
This article mainly introduces the implementation of the tween method in the vue project. Return to the top. Now I will share it with you and give it a reference.
1. Scene
tween.js is a js animation library that can generate smooth animation effects
When you What would you do when you want to implement a function of returning to the top? Most people will use document.body.scrollTop =0; writing this way realizes the function,
But to be more delicate, we might as well use tween Let's do it with easing and see how it works.
We have written articles related to tween before, so we won’t introduce them here.
2. Code
<!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> <p id="app"> <p @click="backTop()" class="backTop">Top</p> </p> <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>
3. requestAnimationFrame rewrites the setInterval method:
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) } }) } }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
About the invalidation of fonts and image resources after vue packaging (detailed tutorial)
Using the BootStrap user experience framework in React (Detailed Tutorial)
The above is the detailed content of How to achieve return to top through tween method in vue project. For more information, please follow other related articles on the PHP Chinese website!