If you put input. focus () in a setTimeout for delayed execution, you can obtain the focus.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
(Function (){
Function get (id ){
Return document. getElementById (id );
}
Window. onload = function (){
Get ('makeinput'). onmousedown = function (){
Var input = document. createElement ('input ');
Input. setAttribute ('type', 'text ');
Input. setAttribute ('value', 'test1 ');
Get ('encrapper'). appendChild (input );
Input. focus ();
Input. select ();
}
Get ('makeinput2'). onmousedown = function (){
Var input = document. createElement ('input ');
Input. setAttribute ('type', 'text ');
Input. setAttribute ('value', 'test1 ');
Get ('inpwrapper2'). appendChild (input );
SetTimeout (function (){
Input. focus ();
Input. select ();
}, 0 );
}
Get ('input'). onkeypress = function (){
Get ('preview'). innerHTML = this. value;
}
}
})();
</Script>
<H1> <code> setTimeout </code> <H2> 1. <code> setTimeout </code> <Button id = "makeinput"> Generate input </button>
<P id = "inpwrapper"> </p>
<H2> 2. Use <code> setTimeout </code> <Button id = "makeinput2"> Generate input </button> <P id = "inpwrapper2"> </p>
<H2> 3. Another example <P> <input type = "text" id = "input" value = "/> <span id =" preview "> </span> </p>