这篇文章主要介绍了vue项目tween方法实现返回顶部,现在分享给大家,也给大家做个参考。
一、场景
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>
<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>
三、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)
}
})
}
}
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
关于vue打包后字体和图片资源失效(详细教程)
react中使用bootstrap用户体验框架(详细教程)
通过网页爬虫中cookie自动获取及过期自动更新(详细教程)
以上就是在vue项目中通过tween方法如何实现返回顶部的详细内容。
