English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Javascript에서의 포커스 관리에 대한 상세 요약

포커스 요소

어떤 요소가 포커스를 받을 수 있을까요? 기본적으로, 포커스를 받을 수 있는 것은 폼 요소만입니다. 왜냐하면 폼 요소만이 상호작용할 수 있기 때문입니다.

<input type="text" value="223">

비폼 요소에 포커스를 얻는 방법도 있습니다. 먼저 tabIndex 속성을 설정합니다.-1,한 번 더 focus() 메서드를 호출합니다.

<div id="test" style="height:30px;width:100px;background:lightgreen">div</div>
<button id="btn">div 요소가 포커스를 얻다</button>
<script>
btn.onclick = function(){
 test.tabIndex = -1;
 test.focus(); 
}
test.onfocus = function(){
 this.style.background = 'pink';
}
</script>

activeElement

document.activeElement 속성은 DOM 포커스를 관리하고, 현재 포커스를 얻은 요소를 저장합니다

[주의] 이 속성은 IE 브라우저에서 지원되지 않습니다

<div id="test" style="height:30px;width:100px;background:lightgreen">div</div>
<button id="btn">div 요소가 포커스를 얻다</button>
<script>
console.log(document.activeElement);//<body>
btn.onclick = function(){
 console.log(document.activeElement);//<button>
 test.tabIndex = -1;
 test.focus(); 
 console.log(document.activeElement);//<div>
}
</script>

포커스를 얻다

요소가 포커스를 얻는 방법은 다음과 같습니다4여러 가지 이유로 포함됩니다. 페이지 로드, 사용자 입력(tab 키 누림), focus() 메서드 및 autofocus 속성

【1】페이지 로드

기본적으로, 문서가 최초로 로드된 후, document.activeElement에 저장된 것은 body 요소의 참조입니다. 문서 로드 중에는 document.activeElement의 값은 null입니다

<script>
console.log(document.activeElement);//null
</script>
<body>
<script>
console.log(document.activeElement);//<body>
</script>
</body>

【2】사용자 입력(tab 키 누림)

사용자는 일반적으로 tab 키를 사용하여 포커스를 이동하고, 공백 키를 사용하여 포커스를 활성화할 수 있습니다. 예를 들어, 포커스가 링크에 있을 때, 공백 키를 한 번 누르면 링크로 이동합니다

tab 키에 대해 이야기할 때, tabIndex 속성을 빼놓을 수 없습니다. tabIndex 속성은 현재 HTML 요소 노드가 tab 키로 순회되는지 여부와 순회 우선 순위를 지정합니다

1、tabIndex=-1、tab 키는 현재 요소를 건너뜁니다

2、tabIndex=0이면, tab 키가 현재 요소를 순회합니다. 요소에 tabIndex가 설정되지 않으면, 기본 값은 0입니다

3、tabIndex가 0보다 크면, tab 키가 우선 순회됩니다. 값이 클수록 우선 순위가 낮습니다

다음 코드에서 tab 키를 사용할 때, button의 포커스를 얻는 순서는2、5、1、3

<div id="box">
 <button tabindex="3">1</button>
 <button tabindex="1">2</button>
 <button tabindex="0">3</button>
 <button tabindex="-1">4</button>
 <button tabindex="2">5</button> 
</div>
<script>
box.onkeyup = function(){
 document.activeElement.style.background = 'pink';
}
</script>

【3】focus();

focus() 메서드는 브라우저의 포커스를 양식 필드로 설정하여, 즉 양식 필드를 활성화하고 키보드 이벤트에 응답하도록 합니다

[주의] 이전에 설명한 것처럼, 양식 요소가 아니면 tabIndex를 설정하여-1,그리고 포커스를 받을 수도 있습니다

<span id="test1" style="height:30px;width:100px;">span</span>
<input id="test2" value="input">
<button id="btn1">span 요소가 포커스를 받은 후</button>
<button id="btn2">input 요소가 포커스를 받은 후</button>
<script>
btn1.onclick = function(){test1.tabIndex=-1;test1.focus();}
btn2.onclick = function(){test2.focus();}
</script>

【4】autofocus

  HTML5양식 필드에 새로운 autofocus 속성이 추가되었습니다. 이 속성을 설정하면 JavaScript 없이도 해당 필드로 자동으로 포커스를 이동시킬 수 있습니다

[주의] 이 속성은 양식 요소에만 사용할 수 있으며, 일반 요소에도 tabIndex=""을 설정하더라도-1″도 효과가 없습니다

<input autofocus value="abc">

hasFocus()

document.hasFocus() 메서드는 현재 문서에 요소가 활성화되거나 포커스를 받고 있는지 여부를 나타내는 부울 값을 반환합니다. 문서가 포커스를 받았는지 확인하여, 페이지와의 상호작용이 진행 중인지 알 수 있습니다

console.log(document.hasFocus());//true
//이 두 초 내에 다른 탭을 클릭하여 현재 페이지에서 포커스를 떠나게 합니다
setTimeout(function(){
 console.log(document.hasFocus());//false
},2000);

포커스를 잃음

요소가 포커스를 잃게 하기 위해 JavaScript를 사용할 때는 blur() 메서드를 사용해야 합니다

blur() 메서드의 역할은 요소에서 포커스를 제거하는 것입니다. blur() 메서드를 호출할 때는 특정 요소로 포커스를 이동시키지 않습니다; 단지 호출된 메서드의 요소에서 포커스를 제거하는 것에 불과합니다

<input id="test" type="text" value="123">
<button id="btn1">input 요소가 포커스를 받은 후</button>
<button id="btn2">input 요소가 포커스를 잃은 후</button>
<script>
btn1.onclick = function(){test.focus();}
btn2.onclick = function(){test.blur();}
</script>

포커스 이벤트

포커스 이벤트는 페이지가 포커스를 얻거나 잃을 때 발생합니다. 이 이벤트들을 이용하여 document.hasFocus() 메서드와 document.activeElement 속성과 함께 사용하면, 사용자가 페이지에서 어떤 활동을 하고 있는지 알 수 있습니다

포커스 이벤트는 다음과 같이 포함됩니다4개

1、blur

blur 이벤트는 요소가 포커스를 잃을 때 발생합니다. 이 이벤트는 버블링되지 않습니다

2、focus

focus 이벤트는 요소가 포커스를 받을 때 발생합니다. 이 이벤트는 버블링되지 않습니다

3、focusin

focusin 이벤트는 요소가 포커스를 받을 때 발생합니다. 이 이벤트는 focus 이벤트와 동일하지만, 버블링됩니다

4、focusout

focusout 이벤트는 요소가 포커스를 잃을 때 발생합니다. 이 이벤트는 blur 이벤트와 동일하지만, 버블됩니다

[주의] focusin과 focusout 이벤트는 IE 브라우저가 DOM0 단계 이벤트 처리기를 지원하는 외에 다른 브라우저는 모두 DOM2레벨 이벤트 처리기

<div id="box"style="display:inline-block;padding:25px;background-color:lightgreen;">
 <div id="boxIn" style="height: 50px;width: 50px;background-color:pink;">123</div>
</div>
<button id="btn1">내용은123의 div 요소가 포커스를 얻을 때/button>
<button id="btn2">내용은123의 div 요소가 포커스를 잃을 때/button>
<button id="reset">되돌리기</button>
<script>
reset.onclick = function(){history.go();}
//focus() 메서드
btn1.onclick = function(){
 boxIn.tabIndex= -1;
 boxIn.focus();
}
//blur() 메서드
btn2.onclick = function(){
 boxIn.blur();
}
//focusin 이벤트
if(boxIn.addEventListener){
 boxIn.addEventListener('focusin',handler) 
}else{
 boxIn.onfocusin = handler;
}
function handler(){
 this.style.backgroundColor ='lightblue';
}
if(box.addEventListener){
 box.addEventListener('focusin',handler) 
}else{
 box.onfocusin = handler;
} 
//blur 이벤트
function fnBlur(){
 this.style.backgroundColor = 'orange';
}
boxIn.onblur = fnBlur;
box.onblur = fnBlur;
</script>

실행 결과에 따르면, focusin 이벤트는 버블될 수 있지만, blur 이벤트는 버블되지 않습니다 

포커스 이벤트는 양식 표시 및 검증에 자주 사용됩니다

예를 들어, 포커스를 얻을 때 배경색을 변경하면; 포커스를 잃을 때 배경색을 원래대로 되돌리고 검증

<div id="box">
 <input id="input}}1" type="text" placeholder=" تنها عدد وارد کنید">
 <input id="input}}2" type="text" placeholder="한자만 입력 가능"> 
 <span id="tips"></span>
</div>
<script>
if(box.addEventListener){
 box.addEventListener('focusin',fnIn);
 box.addEventListener('focusout',fnOut);
}else{
 box.onfocusin = fnIn;
 box.onfocusout = fnOut;
}
function fnIn(e){
 e = e || event;
 var target = e.target || e.srcElement;
 target.style.backgroundColor = 'lightgreen';
}
function fnOut(e){
 e = e || event;
 var target = e.target || e.srcElement;
 target.style.backgroundColor = 'initial';
 //숫자를��인 텍스트 박스에서
 if(target === input1{
 if(!/^\d*$/.test(target.value.trim())){
 target.focus();
 tips.innerHTML = '숫자만 입력할 수 있습니다. 다시 입력하세요'
 setTimeout(function(){
 tips.innerHTML = ''
 },500);
 }
 }
 //텍스트 박스에서 중국어를��인 경우
 if(target === input2{
 if(!/^[\u4e00-\u9fa5]*$/.test(target.value.trim())){
 target.focus();
 tips.innerHTML = '한자만 입력할 수 있습니다. 다시 입력하세요'
 setTimeout(function(){
 tips.innerHTML = ''
 },500);
 }
 } 
}
</script>

결론

이제 여러분을 위해 总结 한 Javascript에서 포커스 관리에 대한 모든 내용을 소개합니다. 이 기사는 매우 자세하게 설명되었으며, 여러분의 학습과 업무에 참고 가치가 있습니다. 의문이 있으면 댓글을 달아 주세요.

추천 합니다