其他分享
首页 > 其他分享> > vue中的回到顶部

vue中的回到顶部

作者:互联网

<template>
  <div class="main">
    <div class="content">灰色部分是内容部分</div>
    <div class="red">红色部分是内容部分</div>
    <div class="scollTop" id="imgscoll" v-show="isShowimg === true">
      <img src="@/assets/dingbu@3x.png" alt @click="goTop">
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      isShowimg: false,
    }
  },
  mounted(){
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed() {
    document.removeEventListener('scroll', this.handleScroll)
    document.body.scrollTop = document.documentElement.scrollTop = 0
  },
  methods:{
    goTop() {
        // 回到顶部
      document.body.scrollTop = document.documentElement.scrollTop = 0
      this.isShowimg = false
    },
    handleScroll(e) {
      // 滚动操作监听
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      // console.log(scrollTop)
      let offsetTop = 0
      try {
        offsetTop = document.querySelector('.main').offsetTop
      } catch (e) {
        offsetTop = 0
      }
      if (scrollTop > offsetTop) {
        // this.searchBarFixed = true
        // this.scrollStatus = {
        //   display: 'block',
        //   background: '#fff',
        //   h: this.statusBarHeight.h
        // }
        if (scrollTop > 500) {
          this.isShowimg = true
        } else {
          this.isShowimg = false
        }
      } else {
        // this.searchBarFixed = false
        this.isShowimg = false
        // this.scrollStatus = {
        //   display: 'none',
        //   background: 'transparent',
        //   h: 0
        // }
      }
    }
  }
}
</script>
<style>
*{
  margin:0;padding:0;
}
.main{
  width: 100%;
}
.content{
  width: 100%;
  height:60rem;
  background: #eee;
}
.red{
  height:30rem;
  background: #f00;
}
 .scollTop {
    position: fixed;
    bottom: 15rem;
    right: 3rem;
}
.scollTop img{
  width: 5rem;
  height: 5rem; 
}
</style>

注意图片需要自行进行引入

标签:vue,false,isShowimg,顶部,回到,background,offsetTop,scrollTop,document
来源: https://www.cnblogs.com/toughy/p/11806374.html