【问题标题】:Trigger 'touchstart' does not work inside of setTimeout触发器“touchstart”在 setTimeout 内不起作用
【发布时间】:2017-06-14 17:59:20
【问题描述】:

我想在 setTimeout 函数内触发对移动设备输入的关注。这工作正常:

$('input').on('touchstart', function(){
    $(this).focus();
});
$('input').trigger('touchstart');

但是,这不起作用:

setTimeout(function(){
    $('input').on('touchstart', function(){
        $(this).focus();
    });
    $('input').trigger('touchstart');
},200);

占位符消失,就像输入获得焦点一样,但键盘和光标不出现。我不知道为什么。有什么办法可以做到吗?

【问题讨论】:

    标签: javascript jquery ios mobile settimeout


    【解决方案1】:

    将超时与设置侦听器分开:

    // It's ok to listen
    $('input').on('touchstart', function(){
            $(this).focus();
        });
    
    // Trigger only when you want it
    setTimeout(function(){
        $('input').trigger('touchstart');
    },200);
    

    【讨论】:

      【解决方案2】:

      我不知道您为什么需要超时,但这似乎可行。

      $('input').on('touchstart', function() {
        $(this).focus();
      });
      setTimeout(function() {
        $('input').trigger('touchstart');
      }, 200);
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <input type="text" placeholder="foo"></input>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-02
        相关资源
        最近更新 更多