這里是本小白使用時遇到的問題及個人使用的方法可能并不完美,
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端和移動端那幾個瀏覽器都能正常運作,
以上是本人遇到和解決的方法,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/178596.html
標籤:JavaScript
上一篇:簡述http協議
下一篇:1-JavaScript變數
