微信小程序 解决自定义顶部导航栏被键盘挤压的问题

解决思路:

        先把键盘的adjust-position置为false,防止键盘自动挤压。然后计算键盘弹起时,input实际被遮挡的高度,通过代码来上滑相应的距离

wxml代码:

<view style="padding-bottom: {{nav_scroll_height}}px;">
    <input id="myInput" bindfocus="keyboardOcclusion" adjust-position="{{false}}" bindblur="offKeyboardOcclusion"></input>
</view>

id:必须加上一个

bindfocus:input获取焦点的事件

bindblur:input失去焦点的事件

adjust-position:false代表不挤压控件

padding-bottom: {{nav_scroll_height}}px:input需要足够的高度来滑动

js代码:

    data: {
        nav_scroll_height: 0, //键盘挤压时,input被遮挡的高度
    }
    //键盘弹起时,解决键盘遮挡问题
    keyboardOcclusion(e) {
        let windowHeight = wx.getSystemInfoSync().windowHeight;
        const query = wx.createSelectorQuery();
        query.select('#' + e.currentTarget.id).boundingClientRect();
        query.selectViewport().scrollOffset();
        console.log('keyBoardHeight',e.detail.height)
        var that = this;
        query.exec(function(res) {
            let inputBottom = windowHeight - res[0].bottom;
            //如果input没有被键盘遮挡,不做任何事
            if (!res[0] || e.detail.height <= inputBottom) {
                that.setData({ nav_scroll_height: 0 });
                return;
            }
            //获取input被键盘遮挡的高度
            that.setData({
                nav_scroll_height: e.detail.height - inputBottom
            });
            wx.pageScrollTo({   //滑动input被键盘遮挡的距离
                scrollTop: res[1].scrollTop + that.data.nav_scroll_height,   //页面滚动的距离
                duration: 300    //页面滚动速度 单位ms
            });
        })
    },
    //键盘关闭时,解决键盘遮挡问题
    offKeyboardOcclusion() {
        this.setData({nav_scroll_height: 0})
    },

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值