How to set caret(cursor) position in contenteditable element (div)?

后端 未结 10 1530
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 01:41

I have this simple HTML as an example:

text text text
text text text
text text
10条回答
  •  星月不相逢
    2020-11-22 02:32

    If you don't want to use jQuery you can try this approach:

    public setCaretPosition() {
        const editableDiv = document.getElementById('contenteditablediv');
        const lastLine = this.input.nativeElement.innerHTML.replace(/.*?(
    )/g, ''); const selection = window.getSelection(); selection.collapse(editableDiv.childNodes[editableDiv.childNodes.length - 1], lastLine.length); }

    editableDiv you editable element, don't forget to set an id for it. Then you need to get your innerHTML from the element and cut all brake lines. And just set collapse with next arguments.

提交回复
热议问题