思考:為什么要累加?
因為offsetTop返回的是當前對象距離上一層父級節點的距離;
如果元素有多個父級,則必須要累加
請參考:JS中offsetTop、clientTop、scrollTop、offsetTop各位置屬性詳解(含示例圖)
解決辦法:
js: 親測有效
getElementTop (el) { let actualTop = el.offsetTop let current = el.offsetParent while (current !== null) { actualTop += current.offsetTop current = current.offsetParent } return actualTop }
應用實例:
解決移動端鍵盤被遮擋的問題:ps這里鍵盤是手寫的,所以不能啟動原生鍵盤的focus事件,只能手動去修改scrollTop高度,來解決接盤被遮擋
html:
<div class="carNo-block" ref="carnoBlock"> <h2>車輛信息<em class="icon_add" @click="addCarNo"></em> </h2> <div class="multiCar" ref="multiCar"> <!--這里ref渲染出了多個,獲取的時候需要添加index索引--> <ul ref="carNo" class="carNo" v-for="(item, index) in carform" :key="index" @click.stop="getCarNoIndex(index)"> ....... <!--鍵盤組件--> <plate ref="plate" :initialPlate="item.carNo" @plateConfirm="plateConfirm" @emitKeyboard="emitKeyboard(index)" @closeKeyBoard="closeKeyBoard" :disabled="item.disabled"> </plate> </ul> </div> </div>
js:
data () { return: { scroll1: 0 } }, mounted() { this.$nextTick(()=>{ // 監聽頁面滾動元素.recordContent的滾動高度 // console.log("scroll1",document.querySelector('.recordContent').offsetHeight) this.box = document.querySelector('.recordContent') this.box.addEventListener('scroll', function(){ // console.log('監聽滾動事件----') this.scroll1 = document.querySelector('.recordContent').scrollTop console.log("scroll1", this.scroll1) }, false) }) }, destroyed() { // 組件銷毀時,結束監聽 this.box.removeEventListener('scroll',() => { this.scroll1 = document.querySelector('.recordContent').scrollTop },false); }, methods: { getElementTop (el) { let actualTop = el.offsetTop let current = el.offsetParent while (current !== null) { actualTop += current.offsetTop current = current.offsetParent } return actualTop }, emitKeyboard (index) { let offsetTop = this.getElementTop(this.$refs.carNo[index]) let offsetHeight = this.box.offsetHeight let bottom = offsetHeight - (offsetTop - this.scroll1) console.log(bottom, offsetHeight, offsetTop, this.scroll1) this.$nextTick(()=>{ let keyBoardHeight = 240 // document.querySelector('.keyboard-cell').offsetHeight if (bottom > keyBoardHeight) { this.scrollHeight = parseInt(this.scroll1 + 50) } else { this.scrollHeight = parseInt(this.scroll1 + (keyBoardHeight - bottom) + 50) } // if( this.scrollHeight < 0){ this.scroll2 = this.box.scrollTop this.box.scrollTop = this.scrollHeight // console.log('this.scroll1', this.scroll2) // } }) }, closeKeyBoard () { this.box.scrollTop = this.scroll2 }, }