处理Android手机键盘弹起之后挡住页面元素。

本文介绍了一种在移动端网页应用中实现键盘弹起时页面自动调整的解决方案,以确保输入框及其下方操作按钮始终可见。该方案通过监听窗口高度变化并调整页面布局来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一下我的问题:



解决方案如下:

			//	  检测键盘弹起一系列事件
			var changeKeyboard = (function() {
				var clearMonitor, monitorWindowHeight, containerId, btnGroupId,
					isFocus = false,
					blurHandle, init, winHeight = window.innerHeight;//获取窗口高度(不包含滚动条)
				//input 获取焦点,检测可视化高度
				init = function(target) {
					if(!target.dataset.key) return;//true
//					btnGroupId = $('.cont_foot'); //获取按钮
					btnGroupId = document.getElementsByClassName('cont_foot')[0];
					alert(btnGroupId)
					btnGroupId.addClass('hidd');

					setTimeout(function() {
						var newTop = 0;
						!isFocus && monitorWindowHeight();
						isFocus = true;

						containerId = document.querySelector('.main'); //获取最外层大的div
						containerId.style.height = window.innerHeight + 'px';
						newTop = target.getBoundingClientRect().top + containerId.scrollTop;
						containerId.scrollTop = newTop - window.innerHeight + 40;
					}, 500);

				}
				//让当前获取焦点的元素失焦
				blurHandle = function() {
					var el = document.activeElement;
					$(el).blur();
				};

				//监听window高度的变化
				monitorWindowHeight = function() {
					clearMonitor = setInterval(function() {
						var heightStr, wh = window.innerHeight;
						if(winHeight == wh) {
							heightStr = "auto";
							btnGroupId && btnGroupId.removeClass('hidd');
							clearInterval(clearMonitor);
							blurHandle();
							isFocus = false;
						} else {
							heightStr = wh + "px";
						}
						containerId.style.height = heightStr;
					}, 500);
				};
				return {
					blurHandle: blurHandle,
					init: init
				}

			})();
			
			var  ua = navigator.userAgent.toLowerCase(); 
			var IS_ANDROID = ua.indexOf('android') != -1;
//			if(ua.indexOf('android') != -1){
//				
//				}
//			
			//监听touch事件,是否来源input
					var blurOut = 0;
					$('body').on('tap',function(e){
						if(e.target.tagName === 'INPUT'||e.target.tagName === 'TEXTAREA'){
							IS_ANDROID && changeKeyboard.init(e.target);
							blurOut && clearTimeout(blurOut);
						}else{
							changeKeyboard.blurHandle();
						}
					})

不能达到在苹果手机那样的效果,但是业务需求是满足了。 

如果有大神有更好的解决方案, 不妨分享一下~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值