2017-06-14 4 views
0

setTimeout関数の内部でモバイル上の入力にフォーカスをかけたいと思います。これは正常に動作します:setTimeoutの中でトリガ 'touchstart'が機能しない

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

しかし、これは動作しません:

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

プレースホルダは、入力が焦点を当てていたかのように消えますが、キーボードとカーソルが表示されません。なぜ私は考えていない。この仕事をする方法はありますか?リスナーの設定から

答えて

0

セパレートタイムアウト:

// It's ok to listen 
$('input').on('touchstart', function(){ 
     $(this).focus(); 
    }); 

// Trigger only when you want it 
setTimeout(function(){ 
    $('input').trigger('touchstart'); 
},200); 
0

あなたがタイムアウトを必要とする理由私は知らないが、これは動作するようです。

$('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>

関連する問題