Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Vue is not at the top when entering the page and how to detect the scroll back to the top button

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

本篇内容主要讲解"vue进入页面时不在顶部以及检测滚动返回顶部按钮如何解决",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"vue进入页面时不在顶部以及检测滚动返回顶部按钮如何解决"吧!

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上绑定滚动事件并检测滚动距离

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进入页面时不在顶部以及检测滚动返回顶部按钮如何解决"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report