How to get current caret position in a SCEditor textarea?

风流意气都作罢 提交于 2019-12-11 22:18:33

问题


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,


回答1:


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

e.g.:

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();


来源:https://stackoverflow.com/questions/18477913/how-to-get-current-caret-position-in-a-sceditor-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!