Phương thức blur() trong HTML DOM dùng để xóa focus bàn phím từ một phần tử cụ thể. Sử dụng blur có thể thêm hoặc xóa focus khỏi bất kỳ phần tử HTML nào. Phương thức blur() giúp điều hướng tốt hơn trên trang web vì có thể focus cụ thể vào phần tử dựa trên đầu vào người dùng.
Cú pháp
Cú pháp cho phương thức blur():
Object.blur()
Ví dụ
Dưới đây là ví dụ về phương thức blur():
<!DOCTYPE html> <html> <head> <style> a{ text-decoration:none; font-size:20px; } a:focus, a:active { color: red; text-decoration:underline; font-size:40px; } </style> </head> <body> <a id="Anchor" href="https://example.com">example.com</a> <p>Cho focus hoặc xóa focus…</p> <input type="button" onclick="getfocus()" value="Nhận focus"> <input type="button" onclick="losefocus()" value="Mất focus"> <script> function getfocus() { document.getElementById("Anchor").focus(); } function losefocus() { document.getElementById("Anchor").blur(); } </script> </body> </html>
Kết quả
Ví dụ này sẽ cho kết quả sau:

Khi click “Nhận focus”:

Khi click “Mất focus”, trở về trạng thái gốc:

Giải thích ví dụ:
Tạo anchor tag id “Anchor” href=”https://example.com”:
<a id="Anchor" href="https://example.com">example.com</a>
Định nghĩa hai style cho anchor để phân biệt khi focus/active và khi không:
a{ text-decoration:none; font-size:20px; } a:focus, a:active { color: red; text-decoration:underline; font-size:40px; }
Hai nút “Nhận focus” và “Mất focus” thực thi getfocus() và losefocus():
<input type="button" onclick="getfocus()" value="Nhận focus"> <input type="button" onclick="losefocus()" value="Mất focus">
getfocus() lấy phần tử id “Anchor” (anchor element), thực thi focus() method chuyển style thành a:focus,a:active (màu đỏ, gạch chân, font 40px):
function getfocus() { document.getElementById("Anchor").focus(); }
losefocus() lấy phần tử id “Anchor”, thực thi blur() method mất focus, chuyển về style gốc của <a>:
function losefocus() { document.getElementById("Anchor").blur(); }