写h5的input框时,遇到两个常见的问题,记录一下
解决思路
- andriod上input聚焦,被软键盘时遮挡
js促使input框进入可视区域 - ios在input失焦时,页面被顶起来
js促使页面滑到最顶端 - fixed在bottom的定位,在input聚焦时,设置为相对定位relative,在失焦时,转为绝对定位fixed
解决方法: scrollIntoView()
方法
//html
<input name="phone" type="number" value=""
onblur="inputBlur();" id="inp_dom"
placeholder="请输入您的手机号" />
//js
//andriod在聚焦的时候做兼容
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
if(isAndroid == true){
$('#inp_dom').focus(function(e){
$('.fixed-operation').css('position','relative');
var target = this;
target.scrollIntoViewIfNeeded();
e.target.scrollIntoView({
block: "center"
});
})
}
//ios在失焦的时候做兼容
function inputBlur(){
var u = navigator.userAgent;
var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
$('.fixed-operation').css('position','fixed');
if(isIOS && !$('#inp_dom').is(":focus")){
window.scrollTo({top:0, left:0, behavior:"smooth"});
}
}