亲宝软件园·资讯

展开

vue实现移动端返回顶部

秃头_08 人气:0

HTML:

<template>
 <div class="home">
  <div v-for="ys in 100" :key="ys">
   <p>1</p>
  </div>
  <div @click="back" class="back1" v-show="isShow">▲</div>
 </div>
</template>

JS:

<script>
export default {
 data() {
  return {
   isShow: true
  };
 },

 handleScroll() {// handleScroll 和 methods 是同级
   if (window.pageYOffset > 300) {
    //window.pageYOffset:获取滚动距离
    this.isShow = true;
   } else {
    this.isShow = false;
   }
   // console.log(window.pageYOffset);
  },

 methods: {
  //点击事件:
  back() {
   //返回顶部 $这个地方需要引入在线jq
   //<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   $("html")
    .stop()
    .animate(
     //animate:动画 点击时让它行动
     {
      scrollTop: 0 //距离顶部为0
     },
     1000 //多少时间完成行动
    );
  }
 }
};
</script>

CSS:

<style scoped>
.back1 {
 width: 50px;
 height: 50px;
 background: #eee;
 position: fixed;
 right: 5px;
 bottom: 50px;
 z-index: 1000;
 text-align: center;
 line-height: 50px;
}
</style>

之前小编看到的一篇文章分享给大家:Vue实现返回顶部按钮

<template>
 <div class="scrollTop">
  <div class="backTop"
      @click="backTop">
    <button v-show="flag_scroll">
          返回顶部
    </button>
   </div>
   //数据源
   <div></div>
  </div>
</template>  
<script>
export default {
 name: 'scrollTop',
 data() {
  return {
 
   flag_scroll: false,
   scroll: 0,
  }
 },
 computed: {},
 methods: {
 //返回顶部事件
  backTop() {
   document.getElementsByClassName('scrollTop')[0].scrollTop = 0
  },
  //滑动超过200时显示按钮
  handleScroll() {
   let scrollTop = document.getElementsByClassName('scrollTop')[0]
    .scrollTop
    console.log(scrollTop)
   if (scrollTop > 200) {
    this.flag_scroll = true
   } else {
    this.flag_scroll = false
   }
  },
 },
 mounted() {
  window.addEventListener('scroll', this.handleScroll, true)
 },
 created() { },
}
</script>

<style scoped>
.scrollTop{
 width: 100%;
 height: 100vh;
 overflow-y: scroll;
}
.backTop {
 position: fixed;
 bottom: 50px;
 z-index: 100;
 right: 0;
 background: white;
}
</style>

加载全部内容

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