วิธีการ HTML DOM focus() ใช้สำหรับเน้นองค์ประกอบ HTML ไม่สามารถใช้โฟกัสกับองค์ประกอบ HTML ทั้งหมดได้ ตัวอย่างเช่น คุณไม่สามารถโฟกัสแท็ก
หากต้องการลบโฟกัสออกจากองค์ประกอบ ให้ใช้เมธอด 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 -

เมื่อคลิกปุ่ม BLUR -

ในตัวอย่างข้างต้น −
ขั้นแรก เราได้สร้างกล่องข้อความที่มีรหัส “USR1” และขนาดและค่าคุณสมบัติความยาวสูงสุดเท่ากับ 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() รับองค์ประกอบอินพุตที่มีประเภท "text" โดยใช้เมธอด getElementById() และเปิดใช้งานเมธอด focus() เพื่อกำหนดโฟกัสบนกล่องข้อความซึ่งใช้สไตล์ :focus กับกล่องข้อความของเรา เมธอด disableFocus() รับองค์ประกอบอินพุตที่มี id “USR1” และเรียกใช้เมธอด blur() ซึ่งลบโฟกัสออกจากกล่องข้อความซึ่งใช้สไตล์ css ปกติของเรา นั่นคือจะกลับไปเป็นสไตล์เริ่มต้น -
function enableFocus() {
document.getElementById("USR1").focus();
}
function disableFocus() {
document.getElementById("USR1").blur();
}