自動聚焦 HTML5 屬性的使用


我們從 HTML5 中獲得了巨大的進步。基本的 HTML 現在可以用來執行以前由 JavaScript 和 Flash 處理的任務,例如基本的表單驗證、INPUT 佔位符以及音訊/影片。HTML 中的 autofocus 屬性允許我們在頁面載入時自動將焦點放在元件上,這是一個另一個簡單的功能。

當 autofocus 屬性存在時,頁面載入時 INPUT、TEXTAREA 或 BUTTON 元素已被選中。此屬性在主要目標是收集資訊的頁面上特別有用。

Autofocus HTML5 屬性

根據 autofocus 全域性屬性(這是一個布林屬性),當頁面載入或其所屬的 <dialogue> 顯示時,應將焦點放在某個元素上。每個文件或對話方塊中只能有一個元素具有 autofocus 屬性。如果對多個專案使用,則第一個專案將獲得焦點。

語法

以下是 autofocus HTML5 屬性的語法

<input name="q" autofocus />

讓我們看一下以下示例,以便更好地理解 autofocus HTML5 屬性的使用。

示例

在以下示例中,我們對 input 型別使用 HTML autofocus 屬性。

<!DOCTYPE html>
<html>
   <body>
      <h1>The autofocus attribute</h1>
      <form>
         <label for="fname">User name:</label>
         <input type="text" id="uname" name="uname" autofocus><br><br>
         <label for="fullname">Full name:</label>
         <input type="text" id="lname" name="lname"><br><br>
         <input type="submit">
      </form>
   </body>
</html>

輸出

當指令碼執行時,它將生成一個輸出,其中包含一個允許使用者輸入文字的輸入欄位,並且 username 輸入型別使用了 autofocus,這意味著頁面載入時輸入欄位將獲得焦點。

示例

考慮另一個使用 HTML autofocus 屬性的按鈕示例。

<!DOCTYPE html>
<html>
   <body>
      <h1>The button autofocus attribute</h1>
      <button type="button" autofocus onclick="alert('Welcome To TP')">CLICK</button>
   </body>
</html>

輸出

執行以上指令碼後,輸出視窗將彈出並顯示帶有 autofocus 屬性的 click 按鈕,這使得頁面載入時按鈕獲得焦點。當用戶點選按鈕時,事件被觸發並顯示一個警報。

示例

在下面,我們對 inputtype 使用 datetime-local。

<!DOCTYPE html>
<html>
   <body>
      <h1>The textarea autofocus attribute</h1>
      <textarea rows="3" cols="40" autofocus>
         Mahendra Singh Dhoni is an Indian former international cricketer
         who was captain of the Indian national cricket team in limited-overs
         formats from 2007 to 2017 and in Test cricket from 2008 to 2014.
      </textarea>
   </body> 
</html>

輸出

當指令碼執行時,它將生成一個輸出,其中包含一個文字區域欄位,該欄位填充了帶有 autofocus 的文字,這使得頁面載入時文字區域欄位獲得焦點。

更新於: 2023年10月11日

165 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.