programing

jQuery - 텍스트 영역에서 모든 텍스트 선택

closeapi 2023. 8. 24. 22:04
반응형

jQuery - 텍스트 영역에서 모든 텍스트 선택

텍스트 영역 내부를 클릭하면 전체 콘텐츠가 선택되도록 하려면 어떻게 해야 합니까?

그리고 마지막으로 다시 클릭하면 선택을 취소합니다.

마우스를 사용하여 캐럿을 이동할 때마다 전체 텍스트가 선택될 때 사용자가 짜증을 내는 것을 방지하려면 다음을 사용하여 이 작업을 수행해야 합니다.focus이벤트, 이벤트가 아닙니다.click이벤트. 다음은 작업을 수행하고 가장 간단한 버전을 방지하는 크롬의 문제를 해결합니다(즉, 텍스트 영역의 문제를 호출하는 것).select()의 방법.focus이벤트 핸들러)가 작동하지 않습니다.

jsFiddle: http://jsfiddle.net/NM62A/

코드:

<textarea id="foo">Some text</textarea>

<script type="text/javascript">
    var textBox = document.getElementById("foo");
    textBox.onfocus = function() {
        textBox.select();

        // Work around Chrome's little problem
        textBox.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox.onmouseup = null;
            return false;
        };
    };
</script>

jQuery 버전:

$("#foo").focus(function() {
    var $this = $(this);
    $this.select();

    // Work around Chrome's little problem
    $this.mouseup(function() {
        // Prevent further mouseup intervention
        $this.unbind("mouseup");
        return false;
    });
});

탭 및 크롬 문제에 대한 솔루션과 새로운 jquery 방법으로 더 나은 방법

$("#element").on("focus keyup", function(e){

        var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if(keycode === 9 || !keycode){
            // Hacemos select
            var $this = $(this);
            $this.select();

            // Para Chrome's que da problema
            $this.on("mouseup", function() {
                // Unbindeamos el mouseup
                $this.off("mouseup");
                return false;
            });
        }
    });

저는 이것을 사용하게 되었습니다.

$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});
$('textarea').focus(function() {
    this.select();
}).mouseup(function() {
    return false;
});

약간 짧은 jQuery 버전:

$('your-element').focus(function(e) {
  e.target.select();
  jQuery(e.target).one('mouseup', function(e) {
    e.preventDefault();
  });
});

크롬 코너 케이스를 올바르게 처리합니다.예를 보려면 http://jsfiddle.net/Ztyx/XMkwm/ 을 참조하십시오.

요소에서 텍스트 선택(마우스로 강조 표시하는 것과 유사)

:)

해당 게시물에서 승인된 답변을 사용하여 다음과 같이 함수를 호출할 수 있습니다.

$(function() {
  $('#textareaId').click(function() {
    SelectText('#textareaId');
  });
});

언급URL : https://stackoverflow.com/questions/5797539/jquery-select-all-text-from-a-textarea

반응형