移动端软键盘问题兼容(安卓、IOS)

解决软键盘顶起fixed元素挡住上方其他视图 (IOS下fixed元素会变成absolute,无法归位并随着页面滚动)

// angular.js中 通过封装指令解决 主要思路是通过scrollHeight的前后差值 判断是否弹出软键盘 然后显示或隐藏被顶起的元素即可

// 指令配置如下:

{
        restrict: 'A',
        link: function (scope, element) {

            var h = document.body.scrollHeight;
            window.onresize = function () {

                if (document.body.scrollHeight < h) {
                    element[0].style.display = none;
                    h = document.body.scrollHeight;
                }else{
                    element[0].style.display = blok;
                    h = document.body.scrollHeight;
                }
            }
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题通常可以通过监听软键盘的打开和关闭事件来解决。可以使用 Vue.js 的 `$nextTick()` 方法和 `window.innerHeight` 属性来获取页面高度和视口高度。具体实现步骤如下: 1. 在 `mounted()` 钩子函数中,添加软键盘打开和关闭事件的监听函数。 ```javascript mounted() { window.addEventListener('resize', this.handleResize) window.addEventListener('scroll', this.handleScroll) window.addEventListener('focusin', this.handleFocusIn) window.addEventListener('focusout', this.handleFocusOut) } ``` 2. 实现监听函数,根据软键盘的状态计算页面高度和视口高度,并更新页面的滚动位置。 ```javascript methods: { handleResize() { if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') { this.isKeyboardOpened = true } else { this.isKeyboardOpened = false } this.updateViewportHeight() }, handleScroll() { if (!this.isKeyboardOpened) return this.updateViewportHeight() }, handleFocusIn() { this.isKeyboardOpened = true this.updateViewportHeight() }, handleFocusOut() { this.isKeyboardOpened = false this.updateViewportHeight() }, updateViewportHeight() { const height = window.innerHeight const input = this.$refs.input const inputHeight = input.offsetHeight const inputOffsetTop = input.getBoundingClientRect().top const offset = window.scrollY const scrollHeight = document.body.scrollHeight const keyboardHeight = height - inputHeight - inputOffsetTop + offset if (keyboardHeight > 0) { document.body.style.height = scrollHeight + keyboardHeight + 'px' document.body.style.overflow = 'hidden' window.scrollTo(0, keyboardHeight) } else { document.body.style.height = '' document.body.style.overflow = '' window.scrollTo(0, 0) } } } ``` 3. 在页面中添加输入框,并绑定 ref 属性。 ```html <template> <div> <input type="text" ref="input"> </div> </template> ``` 这样,当软键盘打开时,页面会自动调整滚动位置,避免输入框被遮挡。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值