2017-06-14 56 views
0

我想觸發一個setTimeout函數內部移動設備上的輸入焦點。這工作得很好:觸發器'touchstart'在setTimeout中不起作用

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