本文最后更新于:2022-02-10T07:02:22+00:00
先上个大概代码,晚点有空记得的话补个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 if (now !== prev && isiOS && !window.visualViewport) { now && setTimeout(() => { this.scrollIntoView('audio-componet') }, 1000) !now && window.scrollTo(0, 0) } }
componentWillUnmount() { this.visualViewport(false) }
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) } }
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 }
|