1.backTop/index.vue

 1 <template>
 2     <div class="backtop" v-if="btnFlag" @click="backTop">
 3         <img  class="go-top" src="../../assets/images/huidaodingbu.png" >
 4     </div>
 5 </template>
 6 
 7 <script>
 8     export default {
 9         name: "",
10         data(){
11             return{
12                 btnFlag:false
13             }
14         },
15         mounted () {
16           window.addEventListener('scroll', this.scrollToTop)
17         },
18         destroyed () {
19           window.removeEventListener('scroll', this.scrollToTop)
20         },   
21         methods: {
22           // 点击图片回到顶部方法,加计时器是为了过渡顺滑
23           backTop () {
24               const that = this
25               let timer = setInterval(() => {
26                 let ispeed = Math.floor(-that.scrollTop / 5)
27                 document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
28                 if (that.scrollTop === 0) {
29                   clearInterval(timer)
30                 }
31               }, 16)
32           },
33          
34           // 为了计算距离顶部的高度,当高度大于60显示回顶部图标,小于60则隐藏
35           scrollToTop () {
36             const that = this
37             let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
38             that.scrollTop = scrollTop
39             if (that.scrollTop > 500) {
40               that.btnFlag = true
41             } else {
42               that.btnFlag = false
43             }
44           }
45         }
46     }
47 </script>
48 
49 <style scoped>
50     .backtop{
51         width: 1rem;
52         height: 1rem;
53         background: #fff;
54         border-radius: 50%;
55         position: fixed;
56         bottom: 1.8rem;
57         right: .2rem;
58         display: flex;
59         justify-content: center;
60         align-items: center;
61         z-index: 9998;
62         border: .02rem solid #DEDEDE;
63     }
64     .backtop img{
65         width: 50%;
66         height: 50%;
67     }
68 </style>

2.引入

1 import Backtop from './layouts/backTop'
2 Vue.component('Backtop',Backtop)

3.使用

1 <Backtop></Backtop>

 

posted on 2020-03-29 10:38  幼儿园恶霸  阅读(162)  评论(0编辑  收藏  举报