苹果fixed定位键盘弹出失效问题

本文最后更新于:2 年前

先上个大概代码,晚点有空记得的话补个demo。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
componentDidMount() {
this.visualViewport(true)
}

componentDidUpdate(prevProps) {
const { isFocus: now } = this.props
const { isFocus: prev } = prevProps
// 苹果12及以下版本的兼容处理
if (now !== prev && isiOS && !window.visualViewport) {
now &&
setTimeout(() => {
this.scrollIntoView('audio-componet')
}, 1000)
!now && window.scrollTo(0, 0)
}
}

componentWillUnmount() {
this.visualViewport(false)
}

// 动态监听绑定or解绑
visualViewport(flag = true) {
if (!isiOS) return
const _visualViewport = window.visualViewport
if (!_visualViewport) return
if (flag) {
_visualViewport.addEventListener('resize', this.setKeyBoardHeight)
_visualViewport.addEventListener('scroll', this.setKeyBoardHeight)
} else {
_visualViewport.removeEventListener('resize', this.setKeyBoardHeight)
_visualViewport.removeEventListener('scroll', this.setKeyBoardHeight)
}
}

// 苹果13香计算底部按钮的位置
setKeyBoardHeight = e => {
this.setState({
_height: this.initialInnerHeight - e.target.height
})
}

// 让底部按钮出现后,回到顶部
scrollIntoView(id) {
if (this._lockRightScroll) return
if (this.state._height) return
const el = document.querySelector(`#${id}`)
this._setTimeoutLock && clearTimeout(this._setTimeoutLock)
this._lockRightScroll = true
console.log('offsetTop', el.offsetTop)
setTimeout(() => {
window.scrollTo(0, el.getBoundingClientRect().top)
this._setTimeoutLock = setTimeout(() => {
this.setState({_height: Math.abs(this.getScrollTop())})
window.scrollTo(0, 0)

this._lockRightScroll = false
}, 20)
})
}

// 获取活动了的高度
getScrollTop() {
let scroll_top = 0
if (document.documentElement && document.documentElement.scrollTop) {
scroll_top = document.documentElement.scrollTop
} else if (document.body) {
scroll_top = document.body.scrollTop
}
return scroll_top
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!