vue进入页面时不在顶部,检测滚动返回顶部按钮

2022-10-14,,,,

 这里是本小白使用时遇到的问题及个人使用的方法可能并不完美。

1.监测浏览器滚动条滚动事件及滚动距离

dmounted() {    
     window.addeventlistener("scroll", this.gundong);    
  },
  destroyed() {
     window.removeeventlistener("scroll", this.gundong);
  },
  methods: {
    gundong() {      
      var dis = document.documentelement.scrolltop || window.pageyoffset || document.body.scrolltop;
      if(dis > 120){
        this.flag = true
      }else{
        this.flag = false
      }
    },

一般给window绑定监测事件就能获得window.pageyoffset滚动距离。

 

2.有些时候给body设置了{width:100%,height:100%},之后就需要将事件绑定在document.body,才能获得document.body.scrolltop滚动距离。

       2.1pc端ie/edge有滚动事件但通过document.body.scrolltop获取不到数值。

       2.2移动端火狐浏览器这样设置没问题也能获取document.body.scrolltop,百度浏览器和华为手机自带的浏览器获取不到。以下有解决方法

vue进入页面时不在顶部

  可以在main.js中写入以下

router.aftereach((to, from) => {
  window.scrollto(0,0);
});

 或者用vue-router中的,需要浏览器支持history.pushstate

scrollbehavior (to, from, savedposition) {
  if (savedposition) {
    return savedposition
  } else {
    return { x: 0, y: 0 }
  }
}

如果因为需要设置了body{width:100%,height:100%}以上就不适用了

我是将vue最外层的#app-container也设置了{width:100%;height:100%},如果需要隐藏滚动条这时的样式,

html,body,#app-container{ width: 100%; height: 100%; overflow: scroll;}
html::-webkit-scrollbar, body::-webkit-scrollbar,#app-container::-webkit-scrollbar{width:0px;height:0px;}

此时可以在#app-contianer上绑定滚动事件并检测滚动距离

<div id="app-container"  @scroll="scrollevent($event)">
scrollevent(e) { var dis = e.srcelement.scrolltop; console.log(dis) if (dis > 150) { this.flag = true; } else { this.flag = false; } }

返回顶部按钮

backtop() {
   this.$el.scrolltop = 0;      
}

进入页面在顶部

var vm = new vue({
  router,
  store,
  render: h => h(app)
}).$mount("#app");

router.aftereach((to, from) => {
  vm.$el.scrolltop = 0;
});

这样在pc端和移动端那几个浏览器都能正常运作。

以上是本人遇到和解决的方法。

《vue进入页面时不在顶部,检测滚动返回顶部按钮.doc》

下载本文的Word格式文档,以方便收藏与打印。