H5解决软键盘弹起导致遮挡输入框问题

本文介绍了一种在移动端Web应用中实现手机软键盘适配的方法。通过监听input元素的聚焦和失焦事件,并结合触摸移动事件,确保了当输入框位于屏幕底部时,能够自动滚动页面,以便用户在弹出软键盘时仍能查看到输入框。

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

            var clientHeight = $(window).height()// 初始化屏幕高度
            var isFocus = false// 是否有input标签被选中,false没有, true有
            var focusDom = null// 当前选中的input标签
            $(document).on('focus', 'input', function (e){// 监听输入框是否选中
                focusDom = $(this)
                $(window).on('touchmove', function() {// 当前页面滚动,收起手机软键盘
                    isFocus = false
                    focusDom.blur()
                })
                if( isFocus ){// 若已有input标签被选中,跳过以下处理
                    return
                }
                
                let bottomHeight = $(window).height() - $(this).height() - $(this).offset().top + $(document).scrollTop()// 当前选中元素距离屏幕底部距离
                // console.log(bottomHeight)
                if( bottomHeight < 300 ){
                    // 若距离底部距离小于300
                    var top = $('#recommended .content').scrollTop()
                    setTimeout(()=>{// 待软键盘弹起动画结束后执行
                        $('#recommended .content').scrollTop(top + 300)// 滚动高度增加300像素,(假设手机软键盘高度为300)
                        isFocus = true
                    }, 300)
                }else{
                    setTimeout(()=>{// 待软键盘收起动画结束后执行
                        isFocus = true
                    }, 300)
                }
                
            })
            $(document).on('blur', 'input', function (){// 收起手机软键盘后,取消监听
                focusDom = null
                if( !document.activeElement ) {// 判断当前是否有focus元素 
                    isFocus = false
                }
                $(window).off('touchmove')
            })
            $(window).resize(function() {// 监听手机软键盘弹起以及收起
                
                if( clientHeight == $(window).height() ){// 手机软键盘收起,使所有input失焦
                    isFocus = false
                    focusDom.blur()
                }
                
            })

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Neo 丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值