h5处理键盘弹出对页面的影响

时间:2024-03-11 17:48:18

1. 键盘弹出触发window.resize,对页面产生挤压,造成定位紊乱

  在页面初始化完成的时候,固定外部容器的宽高,resize的时候也不影响内部dom的相对位置。例如,以body为容器:

<style type="text/css">
	html,body{
		width: 100%;
		height: 100%;
		margin: 0;
		box-sizing: border-box;
	}
	body{
		position: relative;
		overflow-y: scroll;
		scroll-behavior:smooth;
		-webkit-overflow-scrolling: touch;
	}
</style>
<script>
	document.addEventListener(\'DOMContentLoaded\',function(){
		 var fullWidth = window.screen.width;
		 var fullHeight = window.screen.height;
		 if(document.documentElement && document.documentElement.clientHeight){
			 fullWidth = document.documentElement.clientWidth;
			 fullHeight = document.documentElement.clientHeight;
		 }
		 document.body.style.width = fullWidth + "px";
		 document.body.style.height = fullHeight + "px";
	false);
</script>

  

2. 键盘弹出时,输入框被遮挡在键盘下面

  1) 监听resize事件,计算位置并滚动页面到一定距离。例如:

window.onresize = function(){
	// 计算输入框离窗口顶部的距离
	var toTop = document.activeElement.getBoundingClientRect().top;
	// 滚动页面 使输入框距离顶部100px
	window.scrollTo({ 
		top: document.documentElement.scrollTop + (toTop - 100), 
		behavior: "smooth" 
	});
}

  

  2) scrollIntoView方法

window.onresize = function(){
	// 滚动 使输入框处在窗口的中间高度
	document.activeElement.scrollIntoView({
		behavior:"smooth",
		block :"center"
	})
}

  

3. 定义安卓客户端的键盘行为

  不是所有的app在键盘弹出的时候都会造成页面的resize,因为客户端程序可以定义键盘弹出是否影响窗口的大小。

  在安卓项目中,设置对应activity的SoftInputMode为 adjustPan|stateHidden,这样键盘弹出时就会覆盖窗口,而不会挤压窗口造成变形。