美文网首页
Vue中点击按钮回到顶部(滚动效果)

Vue中点击按钮回到顶部(滚动效果)

作者: world_7735 | 来源:发表于2020-04-09 18:02 被阅读0次

页面滚动到一定位置时,出现回到顶部按钮 代码如下

HTML

<div class="footer">
    <div class="gotop" v-show="gotop" @click="toTop">Top</div>
</div>

CSS

.footer .gotop {
  text-align: center;
  position: fixed;
  right: 50px;
  bottom: 30px;
  cursor: pointer;
  padding: 10px;
  border-radius: 50%;
  background: white;
  color: #000000;
}

JS

export default {
  data() {
    return {
      gotop: false
    };
  },
  mounted() {
  // 此处true需要加上,不加滚动事件可能绑定不成功
    window.addEventListener("scroll", this.handleScroll, true);
  },
  methods: {
    handleScroll() {

       let scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
      scrolltop > 30 ? (this.gotop = true) : (this.gotop = false);
    },
    toTop() {
      
      let top = document.documentElement.scrollTop || document.body.scrollTop;
      // 实现滚动效果 
      const timeTop = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
        if (top <= 0) {
          clearInterval(timeTop);
        }
      }, 10);
    }
  }
}

谷歌,火狐,Edge中测试通过,

直接回到顶部

// 滚动到app所在的位置(无滚动效果),如app在顶部,即回到顶部

document.getElementById("app").scrollIntoView();

相关文章

网友评论

      本文标题:Vue中点击按钮回到顶部(滚动效果)

      本文链接:https://www.haomeiwen.com/subject/lgyqmhtx.html