亲宝软件园·资讯

展开

vue实现滑动超出指定距离回顶部功能

人气:0

效果图展示:

1、当页面滑动时执行scrollToTop ()函数,判断滑动的距离是否超出指定距离,注意下面获取getElementsByClassName时,是你被滑动标签的class。

mounted() {
  window.addEventListener('scroll', this.scrollToTop, true)
 }
scrollToTop () {
  let This = this
  let dom = document.getElementsByClassName('content')[0];//获取滑动模块的信息(注意class别写错)
  This.scrollTop = dom.scrollTop;
  if (This.scrollTop > 200) {
    This.btnFlag = true
  } else {
    This.btnFlag = false
  }
}

2、当超出指定距离会出来向上的小图标,点击执行backTop ()函数回顶部。图标我是用的阿里矢量图标引入到项目中,样式自己调一下。

// 点击图标回到顶部方法,加计时器是为了缓慢回到顶部
backTop () {
  let This = this
  let timer = setInterval(() => {
    let ispeed = Math.floor(-This.scrollTop / 5)
    document.getElementsByClassName('content')[0].scrollTop = This.scrollTop + ispeed
    if (This.scrollTop === 0) {
      clearInterval(timer)
    }
  }, 16)
},

完整代码请看下面:

<template>
 <div class="scrollTop-wrap">
  <div v-if="btnFlag" class="go-top">
    <li class="iconfont iconhuidaodingbu" @click="backTop()"></li>
  </div>
 </div>
</template>
<script>
 import { httpGetMethod } from '../common/httpService'
 export default {
  name: 'scrollTop',
  data: function () {
   return {
    btnFlag:false,
    scrollTop:0//当前滑动距离
   }
  },
  mounted() {
    window.addEventListener('scroll', this.scrollToTop, true)
  },
  destroyed () {
    window.removeEventListener('scroll', this.scrollToTop, true)
  },
  methods: {
    // 点击图标回到顶部方法,加计时器是为了缓慢回到顶部
    backTop () {
      let This = this
      let timer = setInterval(() => {
        let ispeed = Math.floor(-This.scrollTop / 5)
        document.getElementsByClassName('content')[0].scrollTop = This.scrollTop + ispeed
        if (This.scrollTop === 0) {
          clearInterval(timer)
        }
      }, 16)
    },
    // 计算距离顶部的高度,当高度大于200显示回顶部图标,小于200则隐藏
    scrollToTop () {
      let This = this
      let dom = document.getElementsByClassName('content')[0];//获取滑动模块的信息(注意class别写错)
      This.scrollTop = dom.scrollTop;
      if (This.scrollTop > 200) {
        This.btnFlag = true
      } else {
        This.btnFlag = false
      }
    }
  }
 }
</script>
<style lang="scss">
 @import '../styles/mixin';
 .scrollTop-wrap {
  position: relative;
  .go-top{
   position: absolute;
   top: 430px;
   left: 260px;
   z-index: 15;
   .iconhuidaodingbu{
     font-size: 30px;
     color: #87878A;
     background-color:#fff;
     border-radius: 50%;
   }
  }
 }
</style>

在其他页面引用一下:

<template>
 <div class="wtll-wrap">
  <div calss="content">
     这里是你的滑动内容
  </div>
  <scrollTop></scrollTop>
 </div>
</template>
<script>
 import scrollTop from '../components/scrollTop'
 export default {
  name: 'wtll',
  data: function () {
   return {
   }
  },
  components: {
   scrollTop
  },
  methods: {
  }
 }
</script>
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论