第一次使用vue做项目,UI选择了Element-ui,看到官网有点击回到顶部按钮,并且按钮是在滚动一段距离后才出现的(附带动画),但是官网文档并没有这个组件,于是自己实现了一个。

首先说明,为了使用美化的的滚动条,这里使用了element的隐藏组件 el-scrollbar,所以滚动条滚动不是相对body(document)进行计算了,而是相对于节点 .el-scrollbar>.el-scrollbar__wrap计算的 (这两个类名是组件自动生成的)。

如果要想用 相对于body计算的滚动位置,请看文章最后(只需要修改一下js部分就行了)。

创建ScrollTop.vue组件

  模板部分:

    vue 点击返回顶部组件(默认不显示,滚动一段距离后显示),附带动画。

  js部分

    vue 点击返回顶部组件(默认不显示,滚动一段距离后显示),附带动画。

  css部分

    vue 点击返回顶部组件(默认不显示,滚动一段距离后显示),附带动画。

完整代码在这里,知道这才是你想要的。。(不过还是建议看着敲一遍~)

<template>
  <!--transition标签 按钮出现附带动画-->
  <transition name="el-fade-in">
    <div class="page-component-up" @click="scrollToTop" v-show="toTopShow">
      <i class="el-icon-caret-top"></i>
    </div>
  </transition>
</template>

<script>
  export default {
    data() {
      return {
        toTopShow: false,
      }
    },
    methods: {
      handleScroll() {
        //id scroller-box是自己在组件上添加的,为了方便获取dom
        this.scrollTop = document.getElementById("scroller-box").children[0].scrollTop
        if (this.scrollTop > 300) {
          this.toTopShow = true
        }else {
          this.toTopShow = false
        }
      },
      scrollToTop() {
        let timer = null, _that = this
        //动画,使用requestAnimationFrame代替setInterval
        cancelAnimationFrame(timer)
        timer = requestAnimationFrame(function fn() {
          if (_that.scrollTop > 0) {
            _that.scrollTop -= 50
            document.getElementById("scroller-box").children[0].scrollTop = _that.scrollTop
            timer = requestAnimationFrame(fn)
          } else {
            cancelAnimationFrame(timer)
            _that.toTopShow = false
          }
        })
      }
    },
    mounted() {
    //$nextTick 避免dom未加载
      this.$nextTick(function () {
        let targetScroll = document.getElementById("scroller-box").children[0]
        targetScroll.addEventListener('scroll', this.handleScroll)
      });
    },
    destroyed() {
      let targetScroll = document.getElementById("scroller-box").children[0]
      targetScroll.removeEventListener('scroll', this.handleScroll)
    }
  }
</script>
<style scoped lang="scss">
  .page-component-up{
    background-color: #409eff;
    position: fixed;
    right: 100px;
    bottom: 150px;
    width: 40px;
    height: 40px;
    border-radius: 20px;
    cursor: pointer;
    transition: .3s;
    box-shadow: 0 3px 6px rgba(0, 0, 0, .5);
    z-index: 100;
    .el-icon-caret-top{
      color: #fff;
      display: block;
      line-height: 40px;
      text-align: center;
      font-size: 18px;
    }
    p{
      display: none;
      text-align: center;
      color: #fff;
    }
    &:hover{
      opacity: .8;
    }
  }
</style>
View Code

相关文章:

  • 2022-12-23
  • 2021-09-05
  • 2022-12-23
  • 2021-05-10
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
猜你喜欢
  • 2022-12-23
  • 2021-07-17
  • 2021-12-24
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案