vue.js实现回到顶部动画效果
时间:2021-02-21 14:56:14|栏目:vue|点击: 次
最近使用vue.js做了几个页面,其中有一个回到顶部的动画效果记录下。
html如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>回到顶部</title> <META HTTP-EQUIV="pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"> <META HTTP-EQUIV="expires" CONTENT="0"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/> <link rel="stylesheet" href="./backTop.css" type="text/css"/> </head> <body> <div class="page">1</div> <div class="page">2</div> <div class="page">3</div> <div class="page">4</div> <div class="page">5</div> <div id="back-to-top" class="back-to-top" @click="backToTop" v-show="backTopShow" v-cloak> <span>回到</span> <span>顶部</span> </div> <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script> <script src="./backTop.js" type="text/javascript"></script> </body> </html>
backTop.css如下:
* { margin: 0px; padding: 0px; border: 0; } html, body { width: 100%; height: 100%; position: relative; background: #F2F2F2; overflow-x: hidden; overflow-y: auto; z-index: 1; } [v-cloak] { display: none; } .back-to-top { position: fixed; bottom: 5px; right: 20px; z-index: 100; border-radius: 5px; box-shadow: 0px 0px 2px #222; padding: 8px 10px; cursor: pointer; } .back-to-top:hover { background: #5AC4D1; } .back-to-top:hover span { color: white; } .back-to-top span { display: block; } .page { width: 100%; height: 400px; line-height: 400px; text-align: center; } .page:nth-child(odd) { background: white; }
backTop.js 如下:
var backTopVue = new Vue({ el : "#back-to-top", data : { //是否显示回到顶部 backTopShow : false, // 是否允许操作返回顶部 backTopAllow : true, // 返回顶部所需时间 backSeconds : 100, // 往下滑动多少显示返回顶部(单位:px) showPx : 200 }, mounted : function() { window.addEventListener("scroll", this.backTopShowOperate, true); }, methods : { backTopShowOperate : function() { if (!this.backTopAllow) return; if (document.body.scrollTop > this.showPx) { this.backTopShow = true; } else { this.backTopShow = false; } }, backToTop : function() { if (!this.backTopAllow) return; this.backToTopShow = false; this.backTopAllow = false; var step = document.body.scrollTop / this.backSeconds; var backTopInterval = setInterval(function() { if (document.body.scrollTop > 0) { document.body.scrollTop -= step; } else { backTopVue.backTopAllow = true; clearInterval(backTopInterval); } }, 1); } } });