포커스가 있는 DOM 요소를 확인하려면 어떻게 해야 하나요?
JavaScript에서 현재 포커스가 있는 요소를 알고 싶습니다.DOM을 샅샅이 뒤졌지만 아직 필요한 걸 찾지 못했어요.어떻게 하는 방법이 있을까요?
내가 이걸 찾는 이유:
, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키, 키enter
입력 요소의 표를 탐색합니다.탭은 지금 작동하지만 입력되며 기본적으로 화살표는 작동하지 않습니다.키 핸들링 부분은 설정했지만 이벤트 핸들링 기능에서 포커스를 이동하는 방법을 찾아야 합니다.
를 사용하여 모든 주요 브라우저에서 지원됩니다.
이전에는 어떤 양식 필드에 포커스가 있는지 확인하려고 하면 찾을 수 없었습니다.이전 브라우저 내에서 검출을 에뮬레이트하려면 모든 필드에 "포커스" 이벤트핸들러를 추가하고 마지막 포커스필드를 변수에 기록합니다.마지막으로 초점을 맞춘 필드의 흐림 이벤트 시 변수를 지우려면 "blur" 핸들러를 추가합니다.
를 가 있는 activeElement
(blur), 블러(blur), 블러(blur)를 사용할 수 있습니다document.activeElement.blur()
이됩니다.activeElement
로로 합니다.body
.
관련 링크:
JW에서 설명한 바와 같이 현재 포커스 요소는 브라우저에 의존하지 않는 방법으로 찾을 수 없습니다.그러나 앱이 IE 전용인 경우(일부 앱은...) 다음과 같은 방법으로 찾을 수 있습니다.
document.activeElement
IE는 결국 모든 것이 잘못된 것은 아닌 것 같습니다.이것은 HTML5 드래프트의 일부이며, 적어도 Chrome, Safari, Firefox의 최신 버전에서 지원되는 것 같습니다.
jQuery를 사용할 수 있는 경우 :focus를 지원합니다.버전 1.6+ 를 사용하고 있는 것을 확인해 주세요.
이 스테이트먼트를 사용하면 현재 초점을 맞추고 있는 요소를 얻을 수 있습니다.
$(":focus")
From: jQuery를 사용하여 초점을 맞춘 요소를 선택하는 방법
document.activeElement
이제 HTML5 작업 초안 사양의 일부가 되었지만 일부 메이저/모바일/오래된 브라우저에서는 아직 지원되지 않을 수 있습니다.에 폴백 할 수 있습니다.querySelector
(일부러) 가 있다document.activeElement
document.body
브라우저 창에 포커스가 없는 경우에도 포커스가 없는 경우.
는 이 하여 다시 ada로 .querySelector
조금 더 나은 지원을 해주실 수 있을 것 같아요.
var focused = document.activeElement;
if (!focused || focused == document.body)
focused = null;
else if (document.querySelector)
focused = document.querySelector(":focus");
또 하나 주의해야 할 점은 이들 두 방법의 성능 차이입니다.하는 것은 항상 .activeElement
소유물.이 jsperf.com 테스트를 참조하십시오.
자체로는 by by by by by bydocument.activeElement
는 문서가 포커스가 되어 있지 않은 경우에도 요소를 반환할 수 있습니다(따라서 문서의 포커스가 없는 경우).
이러한 동작을 원할 수도 있고 중요하지 않을 수도 있습니다(예:keydown
이벤트) 단, 실제로 초점을 맞추고 있는 것을 알 필요가 있는 경우는, 추가로 체크할 수 있습니다.
, 않은 경우 초점 요소가 입니다.null
var focused_element = null;
if (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
) {
focused_element = document.activeElement;
}
특정 요소에 포커스가 있는지 확인하는 것은 간단합니다.
var input_focused = document.activeElement === input && document.hasFocus();
초점을 맞추고 있는지 확인하기 위해 다시 한 번 더 복잡합니다.
var anything_is_focused = (
document.hasFocus() &&
document.activeElement !== null &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
);
견고성에 관한 주의:가 체크하는 코드에서document.body
★★★★★★★★★★★★★★★★★」document.documentElement
가 이들 중 하나 또는 "이러다" 중 null
아무것도 집중되지 않을 때.
경우는 되지 않습니다.<body>
어쩌면)<html>
.tabIndex
즉, 실제로 초점을 맞출 수 있습니다.만약 당신이 도서관 같은 것을 쓰고 있고 그것이 튼튼하기를 원한다면, 당신은 아마도 그것을 어떻게든 처리해야 할 것이다.
여기 집중된 요소를 얻기 위한 "한 줄짜리" 버전이 있습니다. 이 버전은 단락 회로에 대해 알아야 하기 때문에 개념적으로 더 복잡합니다. 아시다시피, 읽을 수 있도록 하려면 한 줄에 맞지 않습니다.
당신이 idk1337 hax0r...저기 있어요.
이 때 ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ,|| null
false
아직 얻을 수 .null
document.activeElement
null
var focused_element = (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement &&
document.activeElement
) || null;
특정 요소가 포커스를 맞추고 있는지 여부를 확인하기 위해 이벤트를 사용할 수도 있지만, 이 방법에서는 셋업이 필요하며(해체 가능성이 있습니다), 중요한 것은 초기 상태를 전제로 합니다.
var input_focused = false;
input.addEventListener("focus", function() {
input_focused = true;
});
input.addEventListener("blur", function() {
input_focused = false;
});
이벤트되지 않은 방법을 사용하여 초기 상태 가정을 수정할 수 있지만, 그 대신 이 방법을 사용하는 것이 좋습니다.
document.activeElement
로는 「」가 가 있습니다.<body>
초점을 맞출 수 있는 요소가 없는 경우 요소.요소가 " " " " 가 됩니다.activeElement
초점 요소가 계속 유지됩니다.
중 하나가 않은 는, 베이스의 어프로치를 검토해 .「 」 、 「 2 」 、 「 CSS 」document.querySelector( ':focus' )
.
다음 스니펫은 현재 포커스가 있는 요소를 판별할 때 도움이 됩니다.다음을 브라우저 콘솔에 복사하면 매초 포커스가 있는 현재 요소의 세부 정보가 인쇄됩니다.
setInterval(function() { console.log(document.querySelector(":focus")); }, 1000);
.console.log
전체 요소를 인쇄해도 요소를 정확히 파악하는 데 도움이 되지 않는 경우 다른 요소를 로그아웃할 수 있습니다.
S가 , Joel S의 .document.activeElement
jQuery 。「」를 서포트하고 오래된 document.activeElement
jQuery.data()
''의 값을 합니다.에서는 「」를 사용합니다.document.activeElement
라고 생각합니다.document.activeElement
퍼포먼스가 향상됩니다.
(function($) {
var settings;
$.fn.focusTracker = function(options) {
settings = $.extend({}, $.focusTracker.defaults, options);
if (!document.activeElement) {
this.each(function() {
var $this = $(this).data('hasFocus', false);
$this.focus(function(event) {
$this.data('hasFocus', true);
});
$this.blur(function(event) {
$this.data('hasFocus', false);
});
});
}
return this;
};
$.fn.hasFocus = function() {
if (this.length === 0) { return false; }
if (document.activeElement) {
return this.get(0) === document.activeElement;
}
return this.data('hasFocus');
};
$.focusTracker = {
defaults: {
context: 'body'
},
focusedElement: function(context) {
var focused;
if (!context) { context = settings.context; }
if (document.activeElement) {
if ($(document.activeElement).closest(context).length > 0) {
focused = document.activeElement;
}
} else {
$(':visible:enabled', context).each(function() {
if ($(this).data('hasFocus')) {
focused = this;
return false;
}
});
}
return $(focused);
}
};
})(jQuery);
Mootools에서 다음과 같은 목적으로 사용한 작은 도우미:
FocusTracker = {
startFocusTracking: function() {
this.store('hasFocus', false);
this.addEvent('focus', function() { this.store('hasFocus', true); });
this.addEvent('blur', function() { this.store('hasFocus', false); });
},
hasFocus: function() {
return this.retrieve('hasFocus');
}
}
Element.implement(FocusTracker);
를 가지고 할 수 .el.hasFocus()
이라면startFocusTracking()
이치노
는 JQuery를 합니다.:focus
현재 의사 클래스입니다.JQuery 매뉴얼에서 이 문서를 찾을 경우 W3C CSS 문서를 가리키는 "Selectors" 아래에서 확인하십시오.Chrome, FF, IE 7+로 테스트했습니다.IE에서 동작하려면 ,<!DOCTYPE...
페이지에 .다음으로 포커스가 있는 요소에 ID를 할당했다고 가정하는 예를 나타냅니다.
$(":focus").each(function() {
alert($(this).attr("id") + " has focus!");
});
" " 의 Element
, 을해야 합니다.document.activeElement
""의 인 Text
, 을.document.getSelection().focusNode
.
도움이 됐으면 좋겠다.
jQuery를 사용하는 경우 이를 사용하여 요소가 활성 상태인지 확인할 수 있습니다.
$("input#id").is(":active");
document.activeElement 사용에는 잠재적인 문제가 있습니다.고려사항:
<div contentEditable="true">
<div>Some text</div>
<div>Some text</div>
<div>Some text</div>
</div>
사용자가 inner-div에 초점을 맞춘 경우 document.activeElement는 여전히 outer div를 참조합니다.document.activeElement를 사용하여 어떤 내부 div에 포커스가 있는지 확인할 수 없습니다.
다음 함수는 이를 회피하고 포커스노드를 반환합니다.
function active_node(){
return window.getSelection().anchorNode;
}
초점을 맞춘 요소를 얻으려면 다음을 사용합니다.
function active_element(){
var anchor = window.getSelection().anchorNode;
if(anchor.nodeType == 3){
return anchor.parentNode;
}else if(anchor.nodeType == 1){
return anchor;
}
}
다른 답을 읽고 나 자신을 시험해 보면document.activeElement
는 대부분의 브라우저에서 필요한 요소를 제공합니다.
문서를 지원하지 않는 브라우저가 있는 경우, jQuery를 가지고 있는 경우, jQuery를 다음과 같은 매우 간단한 방법으로 모든 포커스 이벤트에 채울 수 있습니다(이러한 기준을 충족하는 브라우저가 없기 때문에 테스트되지 않았습니다).
if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway
$('*').live('focus', function () { // Attach to all focus events using .live()
document.activeElement = this; // Set activeElement to the element that has been focussed
});
}
dojo에서는 dijit.getFocus()를 사용할 수 있습니다.
결국 제가 생각해낸 해결책을 제시하기 위해 이걸 여기에 두었습니다.
document.activeInputArea라는 속성을 만들고 jQuery의 단축키 애드온을 사용하여 화살표 키, 탭 및 입력 키 입력 이벤트를 트랩하고 입력 요소를 클릭하기 위한 이벤트 핸들러를 만들었습니다.
그 후 포커스가 바뀔 때마다 activeInputArea를 조정했습니다.그러면 그 속성을 사용하여 자신의 위치를 알 수 있습니다.
단, 시스템에 버그가 있어 포커스가 생각대로 되지 않으면 포커스를 올바르게 되돌리기가 매우 어렵습니다.
document.activeElement를 사용하여 현재 활성 요소를 찾습니다.
document.activeElement.id
★★.id
는, 하는 것을 해, 할 수 있도록 .
개발 도구에 초점을 맞춘 요소를 테스트하고 싶다면 사용을 권장합니다.
$(":focus")
~로document.activeElement
바뀌게 됩니다.body
개발 도구에서 아무 항목이나 클릭하면 됩니다.
이전 활성 요소를 가져오려면 이 항목을 추가합니다.
예: 버튼을 클릭하면 이전 활성 요소가 필요합니다.버튼을 클릭하면 포커스가 잡히니까.
document.addEventListener("focusout",ev => {
document.previousActiveElement = ev.target;
});
언급URL : https://stackoverflow.com/questions/497094/how-do-i-find-out-which-dom-element-has-the-focus
'programing' 카테고리의 다른 글
드라이버 클래스 com.mysql.jdbc를 로드할 수 없습니다.드라이버 스프링 (0) | 2022.09.28 |
---|---|
해시 테이블 VS 관련 어레이 (0) | 2022.09.28 |
오브젝트가 있으면 어떻게 가져오고, 없으면 없음으로 가져오나요? (0) | 2022.09.28 |
Javascript에서 현재 포맷된 날짜 dd/mm/yyy를 가져와 입력에 추가하는 방법 (0) | 2022.09.28 |
MySQL 그룹이 느려지는 이유는 무엇입니까? (0) | 2022.09.28 |