移动端ios输入框自动聚焦问题

之前有遇到关于input聚焦的问题,但是一直没总结。今天有时间就整理总结以下。

一. autofocus 在pc/安卓手机上都有效,但是在ios的safari浏览器上不起作用。

因此对于ios手机上input自动聚焦问题,需要特殊处理下。

二.ios手机上,input的focus事件需要通过用户交互才能触发。

当按钮和input框在同一个页面时,可以通过切换display状态,来显示input框,并且让其自动聚焦。如果按钮和input框属于不同的页面,则暂时不知道解决方案。

示例代码:

 btn.addEventListener('click',function(){
    document.getElementById('input').focus();
});

完整demo代码:

<template>
    <div class="pg-test-wrapper">
        <button id="showModalBtn">显示input</button>
        <div class=" modal-wrapper" v-show="showInput">
            <div class="mask" @click.stop="showInput=false;"></div>
            <div class="content">
                <input
                       id="testInput"
                       v-model="inputValue"
                       autofocus="autofocus"
                       ref="input" />
            </div>
        </div>
    </div>
</template>
<script>

<script>

export default {
    data () {
        return {
            showInput: false,
            inputValue: "测试"
        }
    },

    mounted () {
        //修复在ios11-13的手机上,输入法消失后,页面不回弹的bug
        document.body.addEventListener('focusout', () => {
            let wHeight = document.body.clientHeight || document.documentElement.clientHeight;
            window.scrollTo(0, wHeight);
        });

        document.getElementById("showModalBtn").addEventListener("click", () => {
            this.showInput = true;
            //使用nextTick,让input框自动聚焦(ios和安卓手机都可以)
            this.$nextTick(() => {
                this.$refs.input.focus();
            });

            //this.$refs.input.focus(); //没有作用 不懂原因? 之前有试过这样写是可以让input聚焦的

            // focus方法写在setTimeout里面不起作用
            // setTimeout(() => {
            //this.$refs.input.focus();
            // }, 1000);
        })

    }

}
</script>
<style lang="less" scoped>
button {
    margin: 200px auto 0;
    width: 100px;
    display: block;
}
.modal-wrapper {
    position: relative;
    width: 100%;
    height: 100vh;
}
.mask {
    position: fixed;
    z-index: 10;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.75);
}
.content {
    width: 270px;
    background: #fff;
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -40%);
    z-index: 20;
}
input {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
}
</style>

参考文章:

http://modaobuwukanchaigong.com/2018/05/09/ios-webview-cant-open-keyboard-for-input-field/

https://www.cnblogs.com/shuiyi/p/5419585.html

猜你喜欢

转载自blog.csdn.net/u012574931/article/details/103702447