在某个页面中需要返回页面顶部,但是在借鉴element-ui的官方例子时并没有实验成功。所以就查了查网上其他的资料整理如下:
1.需要在自己的页面中添加div

<div class="scroll" :class="{show:isActive}">
    <div id="toTop" @click="toTop(step)">&lt;</div>
</div>

2.声明变量isActive和控制速度的变量:

data () {
  return {
    isActive: false
  }
},
props: {
  step:{   //控制速度
      type: Number,
      default: 40  
  }
},

3.在mounted中添加监控页面scroll事件

mounted () {
  window.addEventListener('scroll', this.handleScroll)
},

上述代码中this.handleScroll是函数,“scroll”表示监听的事件名称。
4.handleScroll函数内容

handleScroll (e) {
  if (document.documentElement.scrollTop > 50) {
    this.isActive = true
  } else {
    this.isActive = false
  }
},

5.接下来的是回到顶部函数 toTop()

toTop(step){
  //参数step表示时间间隔的幅度大小,以此来控制速度
  //当回到页面顶部的时候需要将定时器清除
  document.documentElement.scrollTop-=step;
  if (document.documentElement.scrollTop>0) {
      var time=setTimeout(()=>this.toTop(step),15);
  }else {
      clearTimeout(time);
  }
},

6.给标签添加css效果

.scroll{
    position: fixed;
    right: 10px;
    bottom: 60px;
    width: 45px;
    height: 90px;
    cursor: pointer;
    display: none;
}
.scroll>div{
    width: 45px;
    height: 45px;
    transform: rotate(90deg);
    line-height: 45px;
    text-align: center;
    font-size: 35px;
    font-family: "黑体";
    background-color: rgba(0,0,0,.2);
    color: #fff;
}
.scroll>div:hover{
    background-color: rgba(0,0,0,.5);
}
.show{
    display: block;
}

7.接下来是实际效果
在这里插入图片描述
多亏借鉴别的大佬的帖子,然后自己修改了一下。如果有什么不正确的地方,望指正。下面是借鉴大佬的原贴:
https://www.zhangshengrong.com/p/KWa3jVWz1o/

Logo

前往低代码交流专区

更多推荐