我试图放置一个固定底部的 div,当输入字段聚焦时,它保持在底部并位于虚拟键盘上方。在 Android 上,它工作得很好,但在 iOS(safari 和 chrome)上,它似乎根本不起作用。 我尝试了 mozilla web dev 的这个解决方案: 检查第二个示例 但这是我在 ios 上遇到的行为:
一开始
** 滚动并重新聚焦输入后:**
iOS上的resize事件好像不是键盘触发的?
这是我在 React 上使用的代码:
import React, { useState, useEffect } from 'react'
function CustomModal() {
const [bottompos, setBottomPos] = useState('0')
useEffect(() => {
const bottomBar = document.getElementById('bottombar')
const layoutViewport = document.getElementById('layoutViewport')
// Function to update the bottom bar position
function updateBottomBarPosition() {
const viewport = window.visualViewport
const visualViewport = window.visualViewport
const offsetLeft = visualViewport.offsetLeft
const offsetTop =
visualViewport.height -
layoutViewport.getBoundingClientRect().height +
visualViewport.offsetTop
// You could also do this by setting style.left and style.top if you
// use width: 100% instead.
console.log(offsetLeft)
setBottomPos(offsetTop)
bottomBar.style.transform = `translate(${offsetLeft}px, ${offsetTop}px) scale(${
1 / viewport.scale
})`
}
// Attach the update function to both scroll and resize events
window.visualViewport.addEventListener('scroll', updateBottomBarPosition)
// Attach the update function to the resize event of the window
window.addEventListener('resize', updateBottomBarPosition)
// Initial positioning
updateBottomBarPosition()
// Clean up event listeners when the component unmounts
return () => {
window.visualViewport.removeEventListener(
'scroll',
updateBottomBarPosition,
)
window.removeEventListener('resize', updateBottomBarPosition)
}
}, []) // Empty dependency array ensures the effect runs once when mounted
console.log(bottompos)
return (
<div>
<div id="bottombar" style={{ position: 'fixed' }}>
<div> some bottom content here </div>
</div>
<div id="layoutViewport">
<input type="textarea"></input>
</div>
</div>
)
}
export default CustomModal
这与 mozilla dev 的示例代码基本相同。
问题是,有解决办法吗?这已经困扰我一段时间了,我似乎无法找到解决方案
interactive-widget
:
overlays-content
是默认行为:不调整大小,将东西放在上面resizes-content
:调整初始视口的大小resizes-visual
:调整虚拟视口的大小,但不调整初始视口的大小