Skip to content
大纲

回到顶部

组件示例

vue
<template>
  <img
    v-show="visible"
    class="back-to-top"
    src="~@/assets/common/toTop.png"
    @click="backToTop"
  />
</template>

<script>
/**
 * NOTE:
 * - `document.documentElement` 和 `document.body` 只有一个生效
 * - 原先通过 `document.compatMode === 'CSS1Compat' ? document.documentElement : document.body` 进行区分存在安卓端 `documentElement` 无法获取到滚动距离的问题
 * - 故改为直接通过 scrollTop 判断滚动文档的指向
 */

export default {
  data() {
    return {
      visible: false,
    };
  },
  methods: {
    onScroll(ev) {
      let scrollY = window.scrollY || window.pageYOffset;
      let windowHeight = window.innerHeight;
      this.visible = scrollY > windowHeight / 2 ? true : false;
    },
    backToTop() {
      let doc;
      if (document.documentElement.scrollTop) {
        doc = document.documentElement;
      }
      if (document.body.scrollTop) {
        doc = document.body;
      }
      let top = doc.scrollTop;
      let speed = top / 60;
      let interval = 360 / 60;
      let timer = setInterval(() => {
        doc.scrollTop -= speed;
        if (doc.scrollTop < speed) {
          doc.scrollTop = 0;
          clearInterval(timer);
        }
      }, interval);
    },
  },
  created() {
    window.addEventListener("scroll", this.onScroll);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.onScroll);
  },
};
</script>

<style scoped lang="scss">
.back-to-top {
  position: fixed;
  z-index: 9999;
  bottom: 34px;
  right: 8px;
  width: 45px;
  height: 44px;
  cursor: pointer;
}
</style>