如何自动选择文本输入?

时间:2017-01-16 14:08:56

标签: javascript html ajax html5 javascript-events

当我点击页面上的其他元素时,我想要选择一个文本输入(就像我点击了一样)。我无法弄清楚该怎么做?

3 个答案:

答案 0 :(得分:2)

您正在寻找:pure js way



<img src="http://placehold.it/350x150" 
onclick="document.getElementById('target').focus(); return false;">

<input type ="text" id="target"/>
&#13;
&#13;
&#13;

单击图像将焦点设置在文本字段上。

答案 1 :(得分:0)

假设您的输入字段的标识为#input,那么解决方案就是

// Wrapper function needed to ensure that DOM elements have been already rendered.
(function() {

  $( '#input' ).focus(); // jQuery

  document.getElementByID( 'input' ).focus(); // VanillaJS

})();

答案 2 :(得分:0)

试试这个。我没有尝试过。值得注意的是它基于jquery。

//set focus by default
$("your_input").focus();
//if the focus is lost set it again
$("div").focusout(function(){
    $("your_input").focus();
});