2017-06-14 61 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>