source

jQuery로 포커스 요소를 얻는 방법

manysource 2022. 11. 14. 21:47

jQuery로 포커스 요소를 얻는 방법

jQuery를 사용하여 캐럿(커서) 포커스가 있는 입력 요소를 가져오려면 어떻게 해야 합니까?

즉, 입력에 캐럿의 포커스가 있는지 어떤지를 판별하는 방법이 있을까요?

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

어떤 걸로 할까요?jQuery 문서를 인용합니다.

다른 유사 클래스 셀렉터(':'로 시작하는 셀렉터)와 마찬가지로 :focus 앞에 태그 이름 또는 다른 셀렉터("*")를 붙이는 것이 좋습니다.바꿔 말하면, 맨몸은$(':focus')와 동등하다$('*:focus')현재 포커스를 맞추고 있는 요소를 찾고 있는 경우 $( document.activeElement )는 DOM 트리 전체를 검색할 필요 없이 해당 요소를 가져옵니다.

답은 다음과 같습니다.

document.activeElement

요소를 감싸는 jQuery 객체를 원하는 경우:

$(document.activeElement)
$( document.activeElement )

jQuery 문서에서 권장하는 대로 전체 DOM 트리를 검색할 필요 없이 가져옵니다.

Firefox에서 Chrome, IE9 및 Safari 두 가지 방법을 테스트했습니다.

(1).$(document.activeElement)Firefox, Chrome 및 Safari에서 정상적으로 동작합니다.

(2).$(':focus')Firefox 및 Safari에서 정상적으로 동작합니다.

마우스로 이동하여 '이름'을 입력하고 키보드에서 Enter 키를 누른 후 초점 요소를 가져오려고 했습니다.

(1).$(document.activeElement)Firefox, Chrome 및 Safari에서는 예상대로 입력:text:name을 반환하지만 IE9에서는 입력:submit:addPassword를 반환합니다.

(2).$(':focus')Firefox 및 Safari에서는 예상대로 입력: text: name이 반환되지만 IE에서는 아무것도 반환되지 않음

<form action="">
    <div id="block-1" class="border">
        <h4>block-1</h4>
        <input type="text" value="enter name here" name="name"/>            
        <input type="button" value="Add name" name="addName"/>
    </div>
    <div id="block-2" class="border">
        <h4>block-2</h4>
        <input type="text" value="enter password here" name="password"/>            
        <input type="submit" value="Add password" name="addPassword"/>
    </div>
</form>

이것을 시험해 보세요.

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});

어떻게 아무도..

document.activeElement.id

IE8을 사용하고 있으며, 다른 브라우저에서는 테스트하지 않았습니다.저 같은 경우에는 연기하기 전에 필드가 최소 4자 이상이고 집중되어 있는지 확인하기 위해 사용하고 있습니다.네 번째 숫자를 입력하면 트리거됩니다.필드의 ID는 year이다.사용하고 있습니다.

if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
    // action here
}

$(':focus')[0]실제 요소를 제공합니다.

$(':focus')는 일련의 요소를 제공합니다.보통 한 번에 1개의 요소만 초점을 맞춥니다.따라서 여러 요소에 초점을 맞추고 있는 경우에만 이 방법이 더 좋습니다.

시험해 보세요:

$(document).on("click",function(){
    alert(event.target);
    });

포커스가 엘리먼트에 있는지 확인합니다.

if ($('#inputId').is(':focus')) {
    //your code
}

언급URL : https://stackoverflow.com/questions/11277989/how-to-get-the-focused-element-with-jquery