How to get range of characters between @ and caret in contenteditable

末鹿安然 提交于 2019-12-20 07:12:45

问题


I have a contenteditable div and it contains other tags and not only plain text. Only one @ is allowed in. How can I get the range of the characters between @ and caret if such a range exists?


回答1:


Ha that was easier than I thought!. Based on this easy to overlook question: Div "contenteditable" : get and delete word preceding caret I forked its jsfiddle and here is mine working as expected:

http://jsfiddle.net/52m2thu2/1/

function getWordBetweenAtAndCaret(containerEl) {
    var preceding = "",
        sel,
        range,
        precedingRange;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0).cloneRange();
            range.collapse(true);
            range.setStart(containerEl, 0);
            preceding = range.toString();
        }
    } else if ((sel = document.selection) && sel.type != "Control") {
        range = sel.createRange();
        precedingRange = range.duplicate();
        precedingRange.moveToElementText(containerEl);
        precedingRange.setEndPoint("EndToStart", range);
        preceding = precedingRange.text;
    }
    var lastWord = preceding.match(/@(.+)$/i);
    if (lastWord) {
        return lastWord;
    } else {
        return false;
    }
}


来源:https://stackoverflow.com/questions/26728648/how-to-get-range-of-characters-between-and-caret-in-contenteditable

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