简体   繁体   中英

Javascript text range up to caret position

I am using IE 8 and I would like to create a text range in a contenteditable div which should include all text until caret position (known to me in the editableDiv). So far I was able to select all text inside my the div:

 function myFunction(editableDiv, cursorPosition)
 {
    if (document.selection) {
       var range = document.body.createTextRange();
        range.moveToElementText(editableDiv);            
        range.collapse(false);
        range.select();
    }
 }

<div id="myDiv" runat="server" contenteditable="true">

But how can I create a text range that begins with the first character in the div and lasts up to caret position? Thank you very much.

Use the setEndPoint() method of TextRange :

var caretRange = document.selection.createRange();
var preCaretRange = document.body.createTextRange();
preCaretRange.moveToElementText(editableDiv);
preCaretRange.setEndPoint("EndToStart", caretRange);

Obviously you'll need different code for non-IE browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM