键盘遮挡H5输入框解决方案
前言
Hello 大家好! 我是前端 无名
问题
在开发H5活动界面的过程中,不可避免的要用到输入框,很多web前端开发人员一听到需求有输入框,就会想到一会评估工时的时候多评估点时间,因为输入框在移动端兼容会有一些问题。
我们这次先说一个问题:移动端键盘弹起,输入框被遮挡,用户看不到输入的内容。
解决方案
要解决问题,先问一下度娘:
果不其然有一篇文章说的还不错:彻底解决H5中键盘遮挡输入框的问题
方案1:
借助Element.scrollIntoView这个方法来解决,让当前元素滚动到浏览器的可视区域内。我们查看下兼容性:
上面查询的兼容性还是比较好的,结果实际测试下来,android和ios许多机型都是无效。
方案2:
度娘的方案不好使,那我们自己想想:
Element.scrollIntoView 给了我们思路,Element.scrollIntoView 无效,我们不用scrollIntoView,我们采用采用scrollTo方法。
步骤:
我们给有input的页面设置为滑动界面。
在input所在页面同级底部加一个div
input onFocus 的时候,我们给底部div 填充高度,然后延迟去让页面滚动到底部。
失去焦点的时候,我们把底部div的高度设置为0
这种方案按照实现步骤,理论上应该适配性很好。
开始上代码: 我们直接在html上根节点增加class,区分mobile还是pc,以及androd还是ios
function isMobile() { var flag = navigator.userAgent.match( /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i ); if (flag) { return true; } return false; }; function isDeviceIos() { var ua = window.navigator.userAgent.toLowerCase(); if (/iphone|ipad|ipod/.test(ua)) { return true; } else if (/android/.test(ua)) { // bridge = new AndroidBridge(this.initial.bind(this)); } return false; } if (isMobile()) { document.body.classList.add("is-mobile"); if (isDeviceIos()) { document.body.classList.add("is-ios"); } } else { document.body.classList.add("is-pc"); } 复制代码
dom结构:
handleOnFocus = () => { const isMob = isMobile(); this.setState({ placeholder: '', }); if (isMob) { window.setTimeout(() => { const scroll = this.scrollRef.current; if (scroll) { //自己封装组件到底部,其实是scrollTo方法 scroll.scrollToBottom(); } }, 0); } }; render() { return ( <Scroll className="sc-content" ref={this.scrollRef}> <Input onChange={this.setDes} ref={this.inputRef} placeholder={placeholder} className="cur-input" onFocus={this.handleOnFocus} maxLength="10" /> <div className="test-des">测试文本</div> <div className="margin-bottom" /> </Scroll> ); } 复制代码
css结合
.is-mobile { .cur-input:focus ~ .margin-bottom { height: 2.5rem; } &.is-ios { .cur-input:focus ~ .margin-bottom { height: 0; } } } 复制代码
这里会存在移动端键盘收回去,但是H5不知道,下面空白的情况,解决方案:移动端监听键盘KeyboardDown事件,发送通知给H5,H5收到事件主动触发input.blur()
componentDidMount = () => { //监听移动端给的keyboardDown事件 this.keyboardDownListener = addKeyboardDown(this.handleKeyboardDown) } handleKeyboardDown = () => { //主动移除焦点 const inputRef = this.inputRef.current; if (inputRef) { inputRef.blur(); } } 复制代码
结语:
本文主要记录工作中遇到的一些问题和解决方案,大家有好的方案,评论区见!一赞一回,欢迎大家来支持。
作者:qyjandroid
链接:https://juejin.cn/post/7024073766913179685