onfocus 이벤트
정의와 사용법
onfocus 이벤트는 요소가 포커스를 얻을 때 발생합니다.
onfocus 이벤트는 <input>、<select> 및 <a>와 함께 가장 자주 사용됩니다.
훌륭한 팁: onfocus 이벤트는 onblur 이벤트반대로.
훌륭한 팁: onfocus 이벤트는 onfocusin 이벤트。主要区别在于 onfocus 이벤트는 퍼블리시되지 않습니다. 따라서, 요소나 그 자식 요소가 포커스를 얻었는지 확인하려면 onfocusin 이벤트를 사용할 수 있습니다. 하지만, onfocus 이벤트에 대해 addEventListener() 메서드의 useCapture 参数来实现这一点。
实例
例子 1
输入字段获得焦点时执行 JavaScript:
<input type="text" onfocus="myFunction()">
页面下方有更多 TIY 예제.
문법
HTML에서:
<element onfocus="myScript">
JavaScript에서:
object.onfocus = function(){myScript};
JavaScript에서 addEventListener() 메서드를 사용하면:
object.addEventListener("focus", myScript);
주석:Internet Explorer 8 또는 이전 버전은 지원하지 않습니다 addEventListener() 메서드。
기술 세부 사항
버블링: | 지원하지 않음 |
---|---|
취소 가능: | 지원하지 않음 |
이벤트 유형: | FocusEvent |
지원되는 HTML 태그: | 모든 HTML 요소, 제외하고는:<base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> 및 <title> |
DOM 버전: | 레벨 2 이벤트 |
브라우저 지원
이벤트 | 크롬 | IE | 파이어폭스 | 사파리 | 오페라 |
---|---|---|---|---|---|
onfocus | 지원 | 지원 | 지원 | 지원 | 지원 |
더 많은 예제
예제 2
"onfocus"와 "onblur" 이벤트를 함께 사용:
<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
예제 3
포커스를 받은 입력 필드를 비우기:
<!-- 입력 필드가 포커스를 받을 때, 현재 값을 빈 문자열로 대체 --> <input type="text" onfocus="this.value=''" value="Blabla">
예제 4
이벤트 대리: addEventListener()의 useCapture 파라미터를 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>
예제 5
이벤트 대리: focusin 이벤트 사용 (Firefox는 지원하지 않음):
<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>