한 번의 마우스 클릭으로 모든 DIV 텍스트 선택


136

사용자가 DIV를 클릭 할 때 DIV 태그의 내용을 강조 표시 / 선택하는 방법 ... 모든 텍스트가 강조 표시 / 선택되므로 사용자가 마우스로 텍스트를 수동으로 강조 표시 할 필요가 없으며 약간의 텍스트를 그리워?

예를 들어 아래와 같이 DIV가 있다고 가정합니다.

<div id="selectable">http://example.com/page.htm</div>

사용자가 해당 URL을 클릭하면 전체 URL 텍스트가 강조 표시되어 브라우저에서 선택한 텍스트를 쉽게 드래그하거나 마우스 오른쪽 단추를 클릭하여 전체 URL을 복사 할 수 있습니다.

감사!

답변:


194

function selectText(containerid) {
    if (document.selection) { // IE
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>

이제 ID를 인수로 전달해야합니다.이 경우 "선택 가능"하지만 더 광범위하므로 chiborg에서 언급 한 것처럼 jQuery를 사용하지 않고 여러 번 어디서나 사용할 수 있습니다.


8
BTW, 당신은 쉽게 교체 JQuery와 클릭 이벤트 핸들러에이를 설정할 수 있습니다 document.getElementById('selectable')this. 그런 다음 컨테이너의 여러 div와 같이 여러 요소에 기능을 눈에 jQuery('#selectcontainer div').click(selectText);
띄게

3
이것은 Chrome, FF, Safari (Mac) 및 Chrome 및 IE (Windows 9+, 8 테스트되지 않음)에서 제대로 작동합니다. 그러나 iPad Mini (iOS6) 또는 iPhone 4의 Safari에서는 작동하지 않는 것 같습니다. 다른 iOS 또는 Android에 대해서는 확실하지 않습니다.
프로토 타입

1
이 기사에 따르면 if (window.getSelection) {Opera에 대한 쿼리 가 먼저옵니다 ( quirksmode.org/dom/range_intro.html )
프로토 타입

1
이 솔루션은 ie11에서 작동하지 않는 것 같습니다. 왜 그런지 알아?
스위스 미스터

5
Chrome 버전 36 이상에서는 '비 연속 선택이 지원되지 않습니다'라는 오류가 표시됩니다. 해결책은 window.getSelection().removeAllRanges();전에 추가하는 것입니다window.getSelection().addRange(range);
nHaskins

122

2017 업데이트 :

노드의 컨텐츠 호출을 선택하려면 다음을 수행하십시오.

window.getSelection().selectAllChildren(
    document.getElementById(id)
);

이것은 IE9 + (표준 모드)를 포함한 모든 최신 브라우저에서 작동합니다.

실행 가능한 예 :

function select(id) {
  window.getSelection()
    .selectAllChildren(
      document.getElementById("target-div") 
    );
}
#outer-div  { padding: 1rem; background-color: #fff0f0; }
#target-div { padding: 1rem; background-color: #f0fff0; }
button      { margin: 1rem; }
<div id="outer-div">
  <div id="target-div">
    Some content for the 
    <br>Target DIV
  </div>
</div>

<button onclick="select(id);">Click to SELECT Contents of #target-div</button>


더 이상 사용되지 않으므로 아래의 원래 답변은 더 window.getSelection().addRange(range); 이상 사용되지 않습니다.

원래 답변 :

위의 모든 예는 다음을 사용합니다.

    var range = document.createRange();
    range.selectNode( ... );

그러나 문제는 DIV 태그 등을 포함하여 노드 자체를 선택한다는 것입니다.

OP 질문에 따라 노드의 텍스트를 선택하려면 대신 전화해야합니다.

    range.selectNodeContents( ... )

따라서 전체 스 니펫은 다음과 같습니다.

    function selectText( containerid ) {

        var node = document.getElementById( containerid );

        if ( document.selection ) {
            var range = document.body.createTextRange();
            range.moveToElementText( node  );
            range.select();
        } else if ( window.getSelection ) {
            var range = document.createRange();
            range.selectNodeContents( node );
            window.getSelection().removeAllRanges();
            window.getSelection().addRange( range );
        }
    }

this요소의 click리스너 내에있는 한 ID를 기반으로 요소를 가져 오는 대신 사용할 수도 있습니다 .
Zach Saucier

44

순수한 CSS4 솔루션이 있습니다.

.selectable{
    -webkit-touch-callout: all; /* iOS Safari */
    -webkit-user-select: all; /* Safari */
    -khtml-user-select: all; /* Konqueror HTML */
    -moz-user-select: all; /* Firefox */
    -ms-user-select: all; /* Internet Explorer/Edge */
    user-select: all; /* Chrome and Opera */

}

user-selectCSS 모듈 레벨 4 사양으로, 현재 초안 및 비표준 CSS 속성이지만 브라우저는이 속성을 잘 지원합니다 ( # search = user-select 참조) .

MDN 에서 사용자 선택 에 대한 자세한 내용을 읽고 여기에서 w3scools로 재생 하십시오.


3
+1 멋진 멋진 우아한 솔루션! 2017 년 9 월에 테스트되었으며 FireFox 및 Chrome에서 완벽하게 작동 하지만 MICROSOFT EDGE에는 없습니다!? 왜 아니고 어떻게 고칠 아이디어가 있습니까? 감사!

13

Neuroxik의 답변이 정말 도움이되었습니다. 외부 div를 클릭하면 작동하지 않기 때문에 Chrome에만 문제가있었습니다. 새 범위를 추가하기 전에 이전 범위를 제거하여 해결할 수 있습니다.

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection()) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>

9

일반 입력이 아닌 컨텐츠 편집 가능 항목의 경우 selectNode가 아닌 selectNodeContents를 사용해야합니다.

참고 : "document.selection"및 "createTextRange ()"에 대한 모든 참조는 IE 8 이하에 대한 것입니다. 이와 같은 까다로운 작업을 시도하는 경우 해당 몬스터를 지원하지 않아도됩니다.

function selectElemText(elem) {

    //Create a range (a range is a like the selection but invisible)
    var range = document.createRange();

    // Select the entire contents of the element
    range.selectNodeContents(elem);

    // Don't select, just positioning caret:
    // In front 
    // range.collapse();
    // Behind:
    // range.collapse(false);

    // Get the selection object
    var selection = window.getSelection();

    // Remove any current selections
    selection.removeAllRanges();

    // Make the range you have just created the visible selection
    selection.addRange(range);

}

6

텍스트 영역 필드를 사용하면 다음을 사용할 수 있습니다. (Via Google)

<form name="select_all">

    <textarea name="text_area" rows="10" cols="80" 
    onClick="javascript:this.form.text_area.focus();this.form.text_area.select();">

    Text Goes Here 

    </textarea>
</form>

이것이 대부분의 웹 사이트가 그렇게하는 방식입니다. 그들은 CSS로 스타일을 지정하여 텍스트 영역처럼 보이지 않습니다.


왜 안돼 this.focus();this.select();?
Taha Paksu

5

이 스 니펫은 필요한 기능을 제공합니다 . 당신이해야 할 일은 그 div에 fnSelect를 활성화하는 이벤트를 추가하는 것입니다. 완전히 수행해서는 안되고 작동하지 않을 수도있는 빠른 해킹은 다음과 같습니다.

document.getElementById("selectable").onclick(function(){
    fnSelect("selectable");
});

스 니펫에 연결된 것이 포함되었다고 가정합니다.


5

이 함수를 jQuery 플러그인으로 감싸는 것이 유용하다는 것을 알았습니다.

$.fn.selectText = function () {
    return $(this).each(function (index, el) {
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(el);
            window.getSelection().addRange(range);
        }
    });
}

따라서 재사용 가능한 솔루션이됩니다. 그런 다음이 작업을 수행 할 수 있습니다

<div onclick="$(this).selectText()">http://example.com/page.htm</div>

그리고 div에서 테스트를 선택합니다.


1
window.getSelection (). removeAllRanges ()를 호출해야합니다. Josillo의 코드에서와 같이. 또한 : window.getSelect를 첫 번째 옵션으로 사용하는 것이 좋습니다. 이는 HTML5 표준이며 document.selection은 IE8 이전의 이전 IE 대체입니다.
Jan Aagaard

3

이 간단한 솔루션은 어떻습니까? :)

<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">

물론 그것은 당신이 언급 한 것처럼 div 구성이 아니지만 여전히 나를 위해 일하고 있습니다.


1
간결한 솔루션이지만 입력 또는 텍스트 필드 이외의 요소에있는 텍스트를 설명하지는 않습니다.
JoePC 2016 년

3

Niko Lay :이 간단한 솔루션은 어떻습니까? :)

`<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">`

.....

전에 코드 :

<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly">

이후 코드 :

<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly" onclick="this.select();" id="selectable">

이 부분 만 onclick = "this.select ();" 내 코드에서 id = "selectable"이 정상적으로 작동했습니다. 마우스 클릭 한 번으로 코드 상자에서 모두 선택합니다.

도움 Niko Lay에 감사드립니다!


0
$.fn.selectText = function () {
    return $(this).each(function (index, el) {
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(el);
            window.getSelection().addRange(range);
        }
    });
}

addRange가 이전에 추가 한 범위를 제거하기 때문에 위의 답변이 Chrome에서 작동하지 않습니다. CSS로 가짜 선택을 제외하고는 이에 대한 해결책을 찾지 못했습니다.


누군가 에게이 코드는 최신 Chrome 버전에서 테스트하고 작동하는 것으로 도움이 될 수 있습니다. $ .fn.selectText = function () {return $ (this) .each (function (index, el) {if (document. selection) {var range = document.body.createTextRange (); range.moveToElementText (el); range.select ();} else if (window.getSelection) {var range = document.createRange (); range.selectNode (el ); window.getSelection (). removeAllRanges (); window.getSelection (). addRange (range);}}); }
Haider Abbas

0

CSS 속성 user-select를 all로 설정하면 쉽게 달성 할 수 있습니다. 이처럼 :

div.anyClass {
  user-select: all;
}

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.