codememo

Safari 및 Chrome에서 작동하지 않는 jQuery를 사용하여 포커스 텍스트 선택

tipmemo 2023. 10. 30. 21:01
반응형

Safari 및 Chrome에서 작동하지 않는 jQuery를 사용하여 포커스 텍스트 선택

파이어폭스와 IE에서는 작동하지만 크롬과 사파리에서는 실패(오류 없음, 작동하지 않음)하는 다음 jQuery 코드(이 질문과 유사)가 있습니다.해결 방법이 없을까요?

$("#souper_fancy").focus(function() { $(this).select() });

온마우스업 이벤트로 인해 선택이 취소되므로 다음 사항을 추가하기만 하면 됩니다.

$("#souper_fancy").mouseup(function(e){
    e.preventDefault();
});
$('#randomfield').focus(function(event) {
    setTimeout(function() {$('#randomfield').select();}, 0);
});

입력 유형="text" 요소에 대해서도 잘 작동합니다.#super_fancy는 어떤 요소입니까?

$("#souper_fancy").focus(function() {
    $(this).select();
});

마우스 업에서 기본값을 방지하는 것만으로도 텍스트 선택이 항상 ON 상태가 됩니다.마우스업 이벤트는 텍스트 선택을 지울 책임이 있습니다.그러나 기본 동작을 방지하여 마우스를 사용하여 텍스트 선택을 취소할 수는 없습니다.

이를 방지하고 텍스트 선택을 다시 작동시키려면 FOCUS에 플래그를 설정하고, 이를 마우스업에서 읽은 후 재설정하면 향후의 마우스업 이벤트가 예상대로 작동합니다.

$("#souper_fancy").focus(function() {
    $(this).select();

    //set flag for preventing MOUSEUP event....
    $this.data("preventMouseUp", true);
});

$("#souper_fancy").mouseup(function(e) {
    var preventEvent = $this.data("preventMouseUp");

    //only prevent default if the flag is TRUE
    if (preventEvent) {
        e.preventDefault();
    }

    //reset flag so MOUSEUP event deselect the text
    $this.data("preventMouseUp", false);
});

사용하다setSelectionRange()에 대한 콜백 내부에서requestAnimationFrame():

$(document).on('focus', '._selectTextOnFocus', (e) => {
    var input = e.currentTarget;
    var initialType = e.currentTarget.type;

    requestAnimationFrame(() => {
        // input.select() is not supported on iOS
        // If setSelectionRange is use on a number input in Chrome it throws an exception,
        // so here we switch to type text first.
        input.type = "text";
        input.setSelectionRange(0, Number.MAX_SAFE_INTEGER || 9999);
        input.type = initialType;
    });
});

사용하다setSelectionRange()대신에select()부터select()모바일 사파리에서는 작동하지 않습니다(iOS 장치(모바일 사파리)의 입력 필드에서 프로그래밍 방식으로 텍스트 선택 참조).

사용할 때까지 기다려야 합니다.requestAnimationFrame텍스트를 선택하기 전에, 그렇지 않으면 iOS에서 키보드가 뜬 후에 요소가 보기로 올바르게 스크롤되지 않습니다.

사용시setSelectionRange()입력 유형을 다음과 같이 설정하는 것이 중요합니다.text, 그렇지 않으면 Chrome에서 예외가 발생할 수 있습니다(선택 Start/selectionEnd on input type="number"는 Chrome에서 더 이상 허용되지 않음).

IE, Firefox, Chrome, Safari 및 Opera에서 선택할 수 있지만 Firefox, Chrome 및 Safari에서 두 번째로 클릭하여 편집할 수는 없습니다.확실하지는 않지만, 필드에 포커스가 이미 있으므로 커서를 실제로 삽입할 수 없음에도 불구하고(다시 선택하므로) 포커스 이벤트를 다시 발행하기 때문일 수 있습니다.IE와 오페라에서는 그렇지 않은 것처럼 보여서 포커스 이벤트가 다시 발생하지 않고 커서가 삽입됩니다.

저는 이 스택 게시물에서 해당 문제가 없고 모든 브라우저에서 작동하는 더 나은 해결책을 찾았습니다.

크롬에서도 작동해야 합니다.

$("#souper_fancy").focus(function() {
    var tempSouper = $(this);
    setTimeout(function(){
        tempSouper.select();
    },100);
});

setTimeout을 사용할 때 깜박임이 발생하기 때문에 이벤트 기반 솔루션이 또 있습니다.이렇게 하면 '포커스' 이벤트가 '마우스업' 이벤트를 부착하고 이벤트 핸들러가 다시 분리됩니다.

    function selectAllOnFocus(e) {
    if (e.type == "mouseup") { // Prevent default and detach the handler
        console.debug("Mouse is up. Preventing default.");
        e.preventDefault();
        $(e.target).off('mouseup', selectAllOnFocus);
        return;
    }
    $(e.target).select();
    console.debug("Selecting all text");
    $(e.target).on('mouseup', selectAllOnFocus);
}

그런 다음 첫 번째 이벤트를 전송합니다.

    $('.varquantity').on('focus', selectAllOnFocus);

이 문제를 다시 발견한 사람이 있다면 모바일을 포함한 모든 브라우저에서 작동하는 순수 JS 솔루션을 얻었습니다.

<input type="text" value="Hello world..." onFocus="window.setTimeout(() => this.select());">

(setTimeout()이 없으면 Safari, 모바일 Safari 및 MS Edge에서 작동하지 않습니다.)

언급URL : https://stackoverflow.com/questions/1269722/selecting-text-on-focus-using-jquery-not-working-in-safari-and-chrome

반응형