developer tip

contenteditable, 텍스트 끝에 캐럿 설정 (브라우저 간)

copycodes 2020. 8. 14. 07:55
반응형

contenteditable, 텍스트 끝에 캐럿 설정 (브라우저 간)


Chrome 에서 출력 :

<div id="content" contenteditable="true" style="border:1px solid #000;width:500px;height:40px;">
    hey
    <div>what's up?</div>
<div>
<button id="insert_caret"></button>

나는 FF 가 다음과 같이 보일 것이라고 믿습니다 .

hey
<br />
what's up?

그리고 IE에서 :

hey
<p>what's up?</p>

불행히도 모든 브라우저 <br />가 div 또는 p-tag 대신 a 삽입하도록 만드는 좋은 방법이 없습니다 . 또는 적어도 온라인에서 아무것도 찾을 수 없습니다.


어쨌든, 지금 하려는 것은 버튼을 눌렀을캐럿이 텍스트 끝에 설정되기를 원하므로 다음과 같이 보일 것입니다.

hey
what's up?|

이 작업을 수행하는 방법은 모든 브라우저 에서 작동 합니까?

예:

$(document).ready(function()
{
    $('#insert_caret').click(function()
    {
        var ele = $('#content');
        var length = ele.html().length;

        ele.focus();

        //set caret -> end pos
     }
 }

다음 기능은 모든 주요 브라우저에서이를 수행합니다.

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

placeCaretAtEnd( document.querySelector('p') );
p{ padding:.5em; border:1px solid black; }
<p contentEditable>foo bar </p>

Placing the caret at the start is almost identical: it just requires changing the Boolean passed into the calls to collapse(). Here's an example that creates functions for placing the caret at the start and at the end:

function createCaretPlacer(atStart) {
    return function(el) {
        el.focus();
        if (typeof window.getSelection != "undefined"
                && typeof document.createRange != "undefined") {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(atStart);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(atStart);
            textRange.select();
        }
    };
}

var placeCaretAtStart = createCaretPlacer(true);
var placeCaretAtEnd = createCaretPlacer(false);

Unfortunately Tim's excellent answer worked for me only for placing at the end, for placing at the start I had to modify it slightly.

function setCaret(target, isStart) {
  const range = document.createRange();
  const sel = window.getSelection();
  if (isStart){
    const newText = document.createTextNode('');
    target.appendChild(newText);
    range.setStart(target.childNodes[0], 0);
  }
  else {
    range.selectNodeContents(target);
  }
  range.collapse(isStart);
  sel.removeAllRanges();
  sel.addRange(range);
  target.focus();
  target.select();
}

Not sure though if focus() and select() are actually needed.


If you are using the google closure compiler, you can do the following (somewhat simplified from Tim's answer):

function placeCaretAtEnd(el) {
    el.focus();
    range = goog.dom.Range.createFromNodeContents(el);
    range.collapse(false);
    range.select();
}

Here's the same thing in ClojureScript:

(defn place-caret-at-end [el] 
   (.focus el)
   (doto (.createFromNodeContents goog.dom.Range el)
         (.collapse false)
         .select))

I have tested this in Chrome, Safari and FireFox, not sure about IE...

참고URL : https://stackoverflow.com/questions/4233265/contenteditable-set-caret-at-the-end-of-the-text-cross-browser

반응형