Sự kiện onfocus
Định nghĩa và cách sử dụng
Sự kiện onfocus xảy ra khi phần tử được tập trung.
Sự kiện onfocus thường được sử dụng cùng với <input>, <select> và <a>.
Lưu ý: Sự kiện onfocus tương tự như Sự kiện onblurngược lại.
Lưu ý: Sự kiện onfocus tương tự như Sự kiện onfocusin。Sự khác biệt chính là sự kiện onfocus không bề mặt. Do đó, nếu bạn muốn xác định một phần tử hoặc phần tử con có được tập trung hay không, bạn có thể sử dụng sự kiện onfocusin. Tuy nhiên, bạn có thể sử dụng sự kiện onfocus bằng cách Phương thức addEventListener()của useCapture Tham số để thực hiện điều này.
Mô hình
Ví dụ 1
Chạy JavaScript khi trường nhập được tập trung:
<input type="text" onfocus="myFunction()">
Dưới trang web có nhiều ví dụ TIY khác.
Cú pháp
Trong HTML:
<element onfocus="myScript">
Trong JavaScript:
object.onfocus = function(){myScript};
Trong JavaScript, sử dụng phương thức addEventListener():
object.addEventListener("focus", myScript);
Chú thích:Internet Explorer 8 hoặc các phiên bản sớm hơn không hỗ trợ Phương thức addEventListener()。
Technical details
Bubbling: | Not supported |
---|---|
Cancelable: | Not supported |
Event type: | Sự kiện FocusEvent |
HTML tags supported: | Tất cả các phần tử HTML, trừ: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> và <title> |
DOM version: | Level 2 Events |
Browser support
Sự kiện | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onfocus | Support | Support | Support | Support | Support |
More examples
ví dụ 2
Sử dụng sự kiện onfocus và onblur:
<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
ví dụ 3
Xóa trường nhập được tập trung:
<!-- Khi trường nhập được tập trung, thay thế giá trị hiện tại của nó bằng một chuỗi rỗng --> <input type="text" onfocus="this.value=''" value="Blabla">
ví dụ 4
事件委托:thiết lập tham số useCapture của addEventListener() là true:
<form id="myForm"> <input type="text" id="myInput"> </form> <script> var x = document.getElementById("myForm"); x.addEventListener("focus", myFocusFunction, true); x.addEventListener("blur", myBlurFunction, true); function myFocusFunction() { document.getElementById("myInput").style.backgroundColor = "yellow"; } function myBlurFunction() { document.getElementById("myInput").style.backgroundColor = ""; } </script>
ví dụ 5
事件委托:sử dụng sự kiện focusin (Firefox không hỗ trợ):
<form id="myForm"> <input type="text" id="myInput"> </form> <script> var x = document.getElementById("myForm"); x.addEventListener("focusin", myFocusFunction); x.addEventListener("focusout", myBlurFunction); function myFocusFunction() { document.getElementById("myInput").style.backgroundColor = "yellow"; } function myBlurFunction() { document.getElementById("myInput").style.backgroundColor = ""; } </script>