한 번의 마우스 클릭으로 모든 DIV 텍스트 선택
사용자가 DIV를 클릭 할 때 DIV 태그의 내용을 강조 표시 / 선택하는 방법 ... 모든 텍스트가 강조 표시 / 선택되므로 사용자가 마우스로 텍스트를 수동으로 강조 표시 할 필요가 없으며 약간의 텍스트를 그리워?
예를 들어 아래와 같이 DIV가 있다고 가정합니다.
<div id="selectable">http://example.com/page.htm</div>
... 사용자가 해당 URL을 클릭하면 전체 URL 텍스트가 강조 표시되어 브라우저에서 선택한 텍스트를 쉽게 드래그하거나 마우스 오른쪽 단추를 클릭하여 전체 URL을 복사 할 수 있습니다.
감사!
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를 사용하지 않고 여러 번 어디서나 사용할 수 있습니다.
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 );
}
}
순수한 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-select
CSS 모듈 수준 4 사양으로, 현재 초안 및 비표준 CSS 속성이지만 브라우저는이 속성을 잘 지원합니다 ( caniuse.com/#feat=user-select 참조) .
MDN 에서 사용자 선택 에 대한 자세한 내용을 읽고 여기에서 w3scools로 재생 하십시오.
The answer of Neuroxik was really helpful. I had only a trouble with Chrome, because when I clicked on an external div, It did not work. I could solve it removing the old ranges before add the new range:
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>
For content editable stuff (not regular inputs, you need to use selectNodeContents (rather than just selectNode).
NOTE: All the references to "document.selection" and "createTextRange()" are for IE 8 and lower... You'll not likely need to support that monster if you're attempting to do tricky stuff like this.
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);
}
Using a text area field, you could use this: (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>
This is how I see most websites do it. They just style it with CSS so it doesn't look like a textarea.
This snippet provides the functionality you require. What you need to do is add an event to that div that which activates fnSelect in it. A quick hack that you totally shouldn't do and possibly might not work, would look like this:
document.getElementById("selectable").onclick(function(){
fnSelect("selectable");
});
Obviously assuming that the linked to snippet had been included.
I found it useful to wrap this function as a jQuery plugin:
$.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);
}
});
}
So, it becomes a reusable solution. Then you can do this:
<div onclick="$(this).selectText()">http://example.com/page.htm</div>
And it will selected test in the div.
How about this simple solution? :)
<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">
Sure it is not div-construction, like you mentioned, but still it is worked for me.
Niko Lay: How about this simple solution? :)
`<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">`
.....
Code before:
<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly">
Code after:
<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly" onclick="this.select();" id="selectable">
Just this part onclick="this.select();" id="selectable" in my code worked fine. Selects all in my code box with one mouse click.
Thanks for help Niko Lay!
$.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);
}
});
}
Above answer is not working in Chrome because addRange remove previous added range. I didnt find any solution for this beside fake selection with css.
Easily achieved with the css property user-select set to all. Like this:
div.anyClass {
user-select: all;
}
참고URL : https://stackoverflow.com/questions/1173194/select-all-div-text-with-single-mouse-click
'Programming' 카테고리의 다른 글
.NET을 사용하여 두 파일을 빠르게 비교하는 방법은 무엇입니까? (0) | 2020.07.05 |
---|---|
팬더 그룹 및 합계 (0) | 2020.07.05 |
문자열을 줄로 나누는 가장 좋은 방법 (0) | 2020.07.05 |
Django 템플릿 내에서 컬렉션의 크기를 어떻게 확인할 수 있습니까? (0) | 2020.07.05 |
클릭 이벤트가 이미 바인딩되어 있는지 확인하는 방법-JQuery (0) | 2020.07.05 |