简体   繁体   中英

How to get current caret position in a SCEditor textarea?

I'm using SCEditor along jQuery in my website and I wonder how can I get the current caret position relative to the beginning of the textarea/div?

I tried things like:

$J('#textarea').sceditor('instance').getRangeHelper().selectedRange().startOffset

but that only gives me the position relative to the current DOM object, not the entire textarea.

What I'm trying to accomplish is to remove all the text after the caret from the textarea. Maybe there is another way to do that.

Thanks,

You can use rangeHelper().saveRange() to insert markers at the start and end of the selection and work from them.

eg:

var sceditor = $("textarea").sceditor("instance");

// Inserts spans with the ID #sceditor-end-start and #sceditor-end-marker
// at the start and end of the current selection
sceditor.getRangeHelper().saveRange();

// Get the DOM node for #sceditor-end-marker and remove all
// nextSiblings and parent nextSiblings from the editor
// which will remove everything after the end of the selection
var node = sceditor.getBody().find('#sceditor-end-marker').get(0);
while (node) {
    while (node.nextSibling)
        node.parentNode.removeChild(node.nextSibling);

    node = node.parentNode;
}

// Restores the selection back to the positions of the
// #sceditor-end-start and #sceditor-end-marker markers
sceditor.getRangeHelper().restoreRange();
sceditor.focus();

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