// 基礎資料
網頁正文全文高: document.body.scrollHeight;
網頁被捲去的高: document.body.scrollTop;
scrollTop 設置或獲取位於對象最頂端和窗口中可見內容的最頂端之間的距離
offsetHeight 獲取對象相對於版面或由父座標 offsetParent 屬性指定的父座標的高度
最近在vuex項目中碰到了這個問題,監聽頁面滾動時 document.body.scrollTop一直都是0,搗鼓了好久最後找到了幾個解決方法
方法一:瀏覽器兼容有問題
寫個兼容方法就行
// chrome || firefox || IE:
// document.documentElement.scrollTop document.body.scrollTop
// safari: window.pageYOffset
let scrollTop= document.documentElement.scrollTop || document.body.scrollTop || window.pageYOffset
方法二:scrollTop的值只有在app.vue頁面纔可以獲取到
① 使用$refs方法獲取頁面實例
mounted(){
var el_ = this.$refs.box;
that.$store.state.el_ = el_;
},
② 在store.js頁面存儲app.vue頁面實例
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from "./mutations"
import actions from "./actions"
import getters from "./getters"
Vue.use(Vuex)
const state = {
el_:'', // app.vue頁面實例
......
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
③ 在需要的頁面調用該實例獲取或修改scrollTop的值
methods: {
scrollTopFun(){
// 獲取scrollTop值
console.log(this.$store.state.el_.scrollTop)
// 修改scrollTop值
this.$store.state.el_.scrollTop = 500 ;
}
}
ok解決完成,親測有效。