HTML DOM focus() 方法用於為 HTML 元素提供焦點。焦點不能應用於所有 HTML 元素。例如:您不能聚焦 <p> 標簽。要從元素中移除焦點,請使用 blur() 方法。
用法
以下是語法 -
HTMLElementObject.focus()
示例
讓我們看一個 focus() 方法的例子 -
<!DOCTYPE html>
<html>
<head>
<style>
input[type=text]:focus, p:active {
color:blue;
font-size:35px;
background-color:lightpink;
border:2px solid blue;
}
input[type=text]{
color:black;
font-size:20px;
}
</style>
<script>
function enableFocus() {
document.getElementById("USR1").focus();
}
function disableFocus() {
document.getElementById("USR1").blur();
}
</script>
</head>
<body>
<h1>focus() method example</h1>
<label>USERNAME:<input id="USR1" type="text" size=5 maxlength=10></label>
<br><br>
<input type="button" onclick="enableFocus()" value="FOCUS">
<input type="button" onclick="disableFocus()" value="BLUR">
</body>
</html>
輸出
這將產生以下輸出 -
單擊 FOCUS 按鈕時 -
單擊“模糊”按鈕 -
在上麵的例子中 -
我們首先創建了一個文本框,id 為 “USR1”,size 和 maxlength 屬性值分別等於 5 和 10。
<label>USERNAME:<input id="USR1" type="text" size=5 maxlength=10></label>
當文本框處於焦點、活動和不處於焦點時,我們創建了兩種不同的 css 樣式 -
input[type=text]:focus, input[type=text]:active { color:blue; font-size:35px; background-color:lightpink; border:2px solid blue; } input[type=text]{ color:black; font-size:20px; }
然後我們創建了兩個按鈕 FOCUS 和 BLUR,當用戶單擊它們時,它們將分別執行 enableFocus() 和 disableFocus() 方法 -
<input type="button" onclick="enableFocus()" value="FOCUS"> <input type="button" onclick="disableFocus()" value="BLUR">
enableFocus() 方法使用 getElementById() 方法獲取 “text” 類型的輸入元素,並啟用其 focus() 方法將焦點設置在文本框上,這將我們的:focus 樣式應用於我們的文本框。 disableFocus() 方法獲取 ID 為 “USR1” 的輸入元素並在其上調用 blur() 方法,該方法從文本框中移除焦點,該文本框將我們的普通 css 樣式應用於它,即它返回到默認樣式 -
function enableFocus() { document.getElementById("USR1").focus(); } function disableFocus() { document.getElementById("USR1").blur(); }
相關用法
- HTML DOM fullscreenEnabled()用法及代碼示例
- HTML DOM Style overflowY屬性用法及代碼示例
- HTML DOM Document hidden屬性用法及代碼示例
- HTML DOM IFrame用法及代碼示例
- HTML DOM Textarea cols屬性用法及代碼示例
- HTML DOM Style pageBreakAfter屬性用法及代碼示例
- HTML DOM Base href屬性用法及代碼示例
- HTML DOM Pre用法及代碼示例
- HTML DOM Input Month用法及代碼示例
- HTML DOM Video canPlayType()用法及代碼示例
- HTML DOM Range deleteContents()用法及代碼示例
- HTML DOM console.dirxml()用法及代碼示例
- HTML DOM Style transition屬性用法及代碼示例
- HTML DOM Video volume屬性用法及代碼示例
- HTML DOM Input Range用法及代碼示例
- HTML DOM Style outlineOffset屬性用法及代碼示例
- HTML DOM Storage setItem()用法及代碼示例
- HTML DOM TableHeader用法及代碼示例
- HTML DOM Style maxWidth屬性用法及代碼示例
- HTML DOM NodeIterator whatToShow屬性用法及代碼示例
注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM focus() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。