Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - focus doesn't work in IE

i have the following function

 function change() 
 {
       var input = document.getElementById('pas');
       var input2 = input.cloneNode(false);
       input2.type = 'password';
       input.parentNode.replaceChild(input2,input);
       input2.focus();
  }

but focus() doesn't work in ie7, so what can i do! i want to have the cursor inside of input!

thanks

update

great solution, thanks, but now it doesn't work in opera:(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For IE you need to use a settimeout function due to it being lazy, for example:

setTimeout(function() { document.getElementById('myInput').focus(); }, 10);

From http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/

For opera, this may help: how to set focus in required index on textbox for opera

UPDATE:

The following snippet of code handles the case when the element is unavailable and retries after a short period - perfect for slow loading pages and/or elements not available until some time after.

setTimeout(

function( ) {

    var el = document.getElementById( "myInput" ) ;
    ( el != null ) ? el.focus( ) : setTimeout( arguments.callee , 10 ) ;

}

, 10 ) ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...