项目场景:
在h5页面,有个输入匹配框,搜索的结果展示在软键盘之上
问题描述:
在安卓手机采用固定定位即可实现,在iOS中固定定位失效,并不能固定在软键盘之上
解决方案:
this.state = {
financingVcResult: false,
};
<div ref={dom => {this.myRef = dom;}}>
<InputItem
{...getFieldProps(`thisVcs${data.id}`, {
normalize: (v, prev) => {
if (v) {
return v.replace(/(^\s*)/g, '');
}
return v;
}
})}
onFocus={this.focusProjectName}
onBlur={name => {
setTimeout(() => {
this.setState({ financingVcResult: false });
}, 50);
}}
/>
</div>
{}
{financingVcResult && (
<div className="financingVcResult">
{this.renderResult(resultList)}
</div>
)}
下面是样式代码
{}
.financingVcResult {
position: absolute;
bottom: 0;
}
下面是js代码
focusProjectName = name => {
this.setState({ financingVcResult: true }, () => {
if (isIOS()) {
window.visualViewport.addEventListener('resize', () => {
var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
if (window.innerHeight - window.visualViewport.height > 0) {
document.getElementsByClassName('financingVcResult')[0].style.bottom =
window.innerHeight -
window.visualViewport.height -
Math.abs(window.innerHeight - this.props.windowInnerHerght) -
scrollHeight +
'px';
return;
}
});
let tip = false;
window.addEventListener('scroll', () => {
if (!tip) {
window.scroll({
top: this.myRef.offsetTop - 40,
behavior: 'smooth'
});
tip = true;
}
var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
if (window.innerHeight - window.visualViewport.height > 0) {
if (scrollHeight > this.myRef.offsetTop) {
let dom = this.myRef;
dom.getElementsByTagName('input')[0].blur();
this.setState({ financingVcResult: false });
}
document.getElementsByClassName('financingVcResult')[0].style.bottom =
window.innerHeight -
window.visualViewport.height -
Math.abs(window.innerHeight - this.props.windowInnerHerght) -
scrollHeight +
'px';
return;
}
});
} else {
document.getElementsByClassName('financingVcResult')[0].style.position ='fixed';
}
});
};
最终效果图
参考链接: js如何获取iOS键盘高度?window.visualViewport简介