JavaScript學習筆記1—焦點定位在頁面表單第一個欄位

來源:互聯網
上載者:User

當我們希望一開啟某個頁面,焦點能夠停留在第一個控制項上的時候,可以寫個簡單的指令碼,
然後放到onload事件處理函數中,比如說下面的一段代碼:

 

<html>
<head>
<title>使用者註冊</title>
</head>
<body onload="document.forms[0].elements[0].focus()">
<form name="form1">
用 戶 名:<input type="text" name="txtName" size="20" /><br />
密    碼:<input type="password" name="txtPassword" size="20" /><br />
確認密碼:<input type="password" name="txtRePassword" size="20" /><br />
電子信箱:<input type="text" name="txtEmail" size="20" /><br />
<input type="submit" name="submitForm1" value="注 冊" /><br />
</form>
</html> 

 

當使用者開啟頁面,焦點是可以定位在第一個欄位的。document.forms[0].elements[0].focus()
表示把游標定位在頁面上第一個表單的第一個元素上,如上例,就是txtName欄位。
但是考慮一下下面的這段代碼:

 

<html>
<head>
<title>使用者註冊</title>
</head>
<body onload="document.forms[0].elements[0].focus()">
<form name="form1">
<input type="hidden" name="txtID" value="123456" /><br />
用 戶 名:<input type="text" name="txtName" size="20" /><br />
密    碼:<input type="password" name="txtPassword" size="20" /><br />
確認密碼:<input type="password" name="txtRePassword" size="20" /><br />
電子信箱:<input type="text" name="txtEmail" size="20" /><br />
<input type="submit" name="submitForm1" value="注 冊" /><br />
</form>
</html> 

 

表單form1的第一個欄位是隱藏欄位,這個欄位是不支援focus()方法的。在這種情況下,將
會出現JavaScript錯誤。並且這個時候我們也不是想把游標定位在那個不可見的欄位上。這
裡的關鍵是把焦點定位在第一個可見的表單欄位上,可以寫個處理的方法:

 

<html>
<head>
<title>使用者註冊</title>
<script type="text/javascript">
//焦點定位在表單第一個可見欄位的方法
function focusOnFirst(){
//檢測頁面是否存在表單
if(document.forms.length>0){
   for(var i=0;i<document.forms[0].elements.length;i++){
       var oField=document.forms[0].elements[i];
       if(oField.type!="hidden"){
          oField.focus();
          return;
        } 
   }
}
}
</script>
</head>
<body onload="focusOnFirst()">
<form name="form1">
<input type="hidden" name="txtID" value="123456" /><br />
用 戶 名:<input type="text" name="txtName" size="20" /><br />
密    碼:<input type="password" name="txtPassword" size="20" /><br />
確認密碼:<input type="password" name="txtRePassword" size="20" /><br />
電子信箱:<input type="text" name="txtEmail" size="20" /><br />
<input type="submit" name="submitForm1" value="注 冊" /><br />
</form>
</html> 

 

測試上面的代碼,游標確實可以定位在第一個表單的第一個可見欄位。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.