code

콘텐츠 편집 가능한 HTML 요소에서 프로그래밍 방식으로 텍스트를 선택 하시겠습니까?

codestyles 2020. 8. 16. 20:22
반응형

콘텐츠 편집 가능한 HTML 요소에서 프로그래밍 방식으로 텍스트를 선택 하시겠습니까?


JavaScript에서는 input또는 textarea요소의 텍스트를 프로그래밍 방식으로 선택할 수 있습니다 . 로 입력에 초점을 맞춘 ipt.focus()다음로 해당 내용을 선택할 수 있습니다 ipt.select(). 을 사용하여 특정 범위를 선택할 수도 있습니다 ipt.setSelectionRange(from,to).

내 질문은 : contenteditable요소에서도 이것을 수행하는 방법이 있습니까?

elem.focus()캐럿을 contenteditable요소 에 넣을 있지만 나중에 실행하면 작동 elem.select()하지 않는다는 것을 알았 습니다 setSelectionRange. 웹에서 아무것도 찾을 수 없지만 잘못된 것을 찾고있는 것 같습니다 ...

그건 그렇고, 차이가 있다면 Chrome 확장 프로그램이기 때문에 Google Chrome에서 작동하기 위해 필요합니다.


Chrome에서 요소의 모든 콘텐츠 (contenteditable 여부)를 선택하려는 경우 방법은 다음과 같습니다. Firefox, Safari 3+, Opera 9+ (아마도 이전 버전도 가능) 및 IE 9에서도 작동합니다. 문자 수준까지 선택 항목을 만들 수도 있습니다. 필요한 API는 DOM 범위 (현재 사양은 DOM 레벨 2 , MDN 참조 )와 선택이며 새 범위 사양 ( MDN 문서 )의 일부로 지정됩니다 .

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var el = document.getElementById("foo");
selectElementContents(el);

Tim Downs 답변 외에도 oldIE에서도 작동하는 솔루션을 만들었습니다.

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

document.getElementById('foo').ondblclick = selectText;​

IE 8+, Firefox 3+, Opera 9+ 및 Chrome 2+에서 테스트되었습니다. 심지어 나는 그것을 jQuery 플러그인으로 설정했습니다.

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

$('#foo').on('dblclick', function() {
  $(this).selectText();
});

... 그리고 누가 관심을 갖고 있는지, 여기 모든 커피 중독자들에게 똑같은 내용이 있습니다.

jQuery.fn.selectText = ->
  @each ->
    if document.body.createTextRange
      range = document.body.createTextRange()
      range.moveToElementText @
      range.select()
    else if window.getSelection
      selection = window.getSelection()
      range = document.createRange()
      range.selectNodeContents @
      selection.removeAllRanges()
      selection.addRange range
    return

최신 정보:

If you want to select the entire page or contents of an editable region (flagged with contentEditable), you can do it much simpler by switching to designMode and using document.execCommand:

There's a good starting point at MDN and a littledocumentation.

var selectText = function () {
  document.execCommand('selectAll', false, null);
};

(works well in IE6+, Opera 9+, Firefoy 3+, Chrome 2+) http://caniuse.com/#search=execCommand


Since all of the existing answers deal with div elements, I'll explain how to do it with spans.

There is a subtle difference when selecting a text range in a span. In order to be able to pass the text start and end index, you have to use a Text node, as described here:

If the startNode is a Node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode.

var e = document.getElementById("id of the span element you want to select text in");
var textNode = e.childNodes[0]; //text node is the first child node of a span

var r = document.createRange();
var startIndex = 0;
var endIndex = textNode.textContent.length;
r.setStart(textNode, startIndex);
r.setEnd(textNode, endIndex);

var s = window.getSelection();
s.removeAllRanges();
s.addRange(r);

Rangy allows you to do this cross-browser with the same code. Rangy is a cross-browser implementation of the DOM methods for selections. It is well tested and makes this a lot less painful. I refuse to touch contenteditable without it.

You can find rangy here:

http://code.google.com/p/rangy/

With rangy in your project, you can always write this, even if the browser is IE 8 or earlier and has a completely different native API for selections:

var range = rangy.createRange();
range.selectNodeContents(contentEditableNode);
var sel = rangy.getSelection();
sel.removeAllRanges();
sel.addRange(range);

Where "contentEditableNode" is the DOM node that has the contenteditable attribute. You might fetch it like this:

var contentEditable = document.getElementById('my-editable-thing');

Or if jQuery is part of your project already and you find it convenient:

var contentEditable = $('.some-selector')[0];

[Updated to fix mistake]

Here is an example that is adapted from this answer that appears to work well in Chrome - Select range in contenteditable div

var elm = document.getElementById("myText"),
    fc = elm.firstChild,
    ec = elm.lastChild,
    range = document.createRange(),
    sel;
elm.focus();
range.setStart(fc,1);
range.setEnd(ec,3);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

HTML is:

<div id="myText" contenteditable>test</div>

contenteditable is just an attribute, that is interpreted by browser. You can modify such elements with ordinary DOM functions.

See javascript TextRanges.

Btw, quick search in SO, gave me couple results.

참고URL : https://stackoverflow.com/questions/6139107/programmatically-select-text-in-a-contenteditable-html-element

반응형