• iOS下调用元素的focus方法,input元素不聚焦,键盘不弹起的问题


    页面元素

    <input type="text" ref="elInput"/>
     
    
    <div
    style="margin-top:20px;"
    @click="confession()"
    ref="elBtn">点击使input聚焦
    </div>
    

    js代码

    methods(){
    confession(){
    this.$refs.elInput.focus()//显示键盘
    }
    }
    

    上述代码在是有效的,但是对于input元素不是一直存在页面上,是动态显示的,上述方法就会失效

    页面元素

    <input v-show="isShow" type="text" ref="elInput"/>
    <div
    style="margin-top:20px;"
    @click="confession()"
    ref="elBtn">点击使input聚焦
    </div>
    

    js代码

    data() {
    return {
    isShow:false
    }
    },
     
    
    methods(){
    confession(){
    this.isShow=true
    this.$nextTick(function(){
    this.$refs.elInput.focus()//显示键盘
    })
    }
    }
    

    上述情况,ios下input聚焦是失效的,可以使用下面的方法(让input一直都在页面中)
    将input写在页面上,利用定位给input显示在用户看不到的地方,当用户点击按钮时,将input定位到指定位置,显示出来
    也可以将input透明度设为0,当用户点击按钮时,将input的透明对设为1

    页面元素

    <input :class="{'is-show':isShow}" type="text" ref="elInput"/>
    <div
    style="margin-top:20px;"
    @click="confession()"
    ref="elBtn">点击使input聚焦
    </div>
    

    js代码

    data() {
    return {
    isShow:false,
    }
    },
     
    
    methods(){
    confession(){
    this.isShow=true
    this.$refs.elInput.focus()//显示键盘
    }
    }
     
    
    <style lang="less" scoped>
    input{
    position:relative;
    left:-1000px;
    }
    .is-show{
    left:0;
    }
    </style>
    

    上面的方法验证成功,注意,confession方法里面的 this.$refs.elInput.focus()这句代码不能放在异步或函数里面,否则也会失效

    原因在于ios有所限制:
    寻常代码里的focus不会生效,除了在某个UI事件(例如click, touchend等)的直接执行环境中调用focus

    注意这个直接环境,它的意思是如果你在setTimeout, promise等异步方式中执行了focus,依然是无效的。

    ios上述限制是出于安全机制的考虑

    ios上只有用户交互触发的focus事件才会起效,而延时回调的focus是不会触发的

  • 相关阅读:
    LightOJ 1203--Guarding Bananas(二维凸包+内角计算)
    断言assert()与调试帮助
    POJ 3528--Ultimate Weapon(三维凸包)
    POJ 2208--Pyramids(欧拉四面体体积计算)
    HDU 1411--校庆神秘建筑(欧拉四面体体积计算)
    HDU 1241 DFS
    HDU 2037(贪心)
    一次傻乎乎的错误QAQ
    封装Qt的SQLite接口类
    最小生成树(Kruskal算法)模板
  • 原文地址:https://www.cnblogs.com/HYZhou2018/p/11159247.html
Copyright © 2020-2023  润新知