페이지로드시 HTML 입력 상자에 초점 설정


96

페이지가로드 될 때 입력 상자에 기본 포커스를 설정하려고합니다 (예 : google). 내 페이지는 매우 간단하지만이 작업을 수행하는 방법을 알 수 없습니다.

이것이 내가 지금까지 얻은 것입니다.

<html>
<head>
 <title>Password Protected Page</title>

 <script type="text/javascript">
 function FocusOnInput()
 {
 document.getElementById("PasswordInput").focus();
 }
 </script>

 <style type="text/css" media="screen">
  body, html {height: 100%; padding: 0px; margin: 0px;}
  #outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}
  #middle {vertical-align: middle}
  #centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}
 </style>
</head>
<body onload="FocusOnInput()">
 <table id="outer" cellpadding="0" cellspacing="0">
  <tr><td id="middle">
   <div id="centered">
  <form action="verify.php" method="post">
   <input type="password" name="PasswordInput"/>
  </form>
   </div>
  </td></tr>
 </table>
</body>
</html>

이것이 잘 작동하는 동안 작동하지 않는 이유는 무엇입니까?

<html>
<head>
<script type="text/javascript">
function FocusOnInput()
{
     document.getElementById("InputID").focus();
}
</script>
</head>

<body onload="FocusOnInput()">
  <form>
       <input type="text" id="InputID">
  </form>
</body>

</html>

도움을 많이 주시면 감사하겠습니다 :-)

답변:


36

이 줄 :

<input type="password" name="PasswordInput"/>

다음 과 같이 id 속성 이 있어야합니다 .

<input type="password" name="PasswordInput" id="PasswordInput"/>

실제로 입력 포커스를 설정합니까? 어떤 브라우저에서 사용해 보셨습니까?
Peter Mortensen

나는 :)이 9 년 ago 테스트 파이어 폭스, 크롬 및 예에 때 @PeterMortensen
Saikios

327

HTML5의 autofocus 속성을 사용할 수 있습니다 (IE9 이하를 제외한 모든 현재 브라우저에서 작동). IE9 또는 이전 버전이거나 다른 브라우저의 이전 버전 인 경우에만 스크립트를 호출하십시오.

<input type="text" name="fname" autofocus>

7
ie9


4
여기에 대한 호환성 테이블의 자동 초점 : caniuse.com/#feat=autofocus
오레오

5

이것은 IE의 일반적인 문제 중 하나이며 이에 대한 수정은 간단합니다. 입력에 .focus ()를 두 번 추가합니다.

수정 :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    element.focus();
    setTimeout(function () { element.focus(); }, 1);
}

그리고 $ (document) .ready (function () {.....}에서 FocusOnInput ()을 호출합니다.


2

다음을 사용할 수도 있습니다.

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />
    </form>
</body>

그리고 JavaScript에서 :

function focusOnInput() {
    document.forms["passwordForm"]["passwordInput"].focus();
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.