获取位于contenteditable div中光标所在位置的单词?

6
我正在尝试从一个可编辑的div中提取单个单词,当鼠标点击时,它应该返回被选中的单词。例如:

Lorem ipsum dolor sit amet, cons|ectetur adipiscing elit. Cras vestibulum gravida tincidunt. Proin justo dolor, iaculis vulputate eleifend et, facilisis eu erat.*

使用|代表光标,函数应该返回"consectetur"。
我的代码:
window.onload = function () {
        document.getElementById("text-editor").onclick = function () {
            var caretPos = 0, containerEl = null, sel, range;
            if (window.getSelection) {
                sel = window.getSelection();
                if (sel.rangeCount) {
                    range = sel.getRangeAt(0);
                    if (range.commonAncestorContainer.parentNode == this) {
                        caretPos = range.endOffset;
                    }
                }
            } else if (document.selection && document.selection.createRange) {
                range = document.selection.createRange();
                if (range.parentElement() == this) {
                    var tempEl = document.createElement("span");
                    this.insertBefore(tempEl, this.firstChild);
                    var tempRange = range.duplicate();
                    tempRange.moveToElementText(tempEl);
                    tempRange.setEndPoint("EndToEnd", range);
                    caretPos = tempRange.text.length;
                }
            }
            var prevSpace, nextSpace, text = this.innerText;
            
            prevSpace = text.substring(0,caretPos).lastIndexOf(" ");
            nextSpace = text.indexOf(" ", caretPos + 1);
            nextSpace == -1 ? nextSpace = text.length - 1 : false;
            prevSpace++;
            console.log([prevSpace,caretPos,nextSpace].join("|"));
            var word = text.substring(prevSpace, nextSpace);
            //Removes punctuation and whitespace.
            var patt = new RegExp("([A-Za-z0-9']*)","g");
            word = patt.exec(word)[0];
            document.getElementById("current-word").innerHTML = word;
        };
    };

一个函数绑定到contenteditable div的鼠标单击事件上,它计算插入符位置并找到前面和后面空格字符的索引(或者整个字符串的开头或结尾),然后使用substring确定单词。有一个快速的正则表达式匹配来删除标点符号和空白字符,最后得到正确的单词。
当contenteditable div中存在单个文本节点时,这很有效,但是一旦开始添加其他标签如br,该方法计算插入符位置的部分停止工作,始终将其计算为0。是否有一种类似于文本的HTML计算插入符位置的方法?
如果没有,有人能提出替代方法吗?

我曾经问过类似的问题,并找到了使用Rangy的另一种解决方案:http://stackoverflow.com/questions/22076945/rangy-word-under-caret-again/22097787#22097787 - Sebastien Lorber
2个回答

17

你可以使用我Rangy库的新TextRange模块来实现这个功能,尽管针对这一个功能它有些过度了。以下是你需要的代码:

var sel = rangy.getSelection();
sel.expand("word");
var word = sel.text();
alert(word);
否则,如果你可以接受不支持旧版Blink Opera(包括版本12及以下)和Firefox < 4的情况,则可以使用 Selection.modify()(WebKit,Firefox)和TextRangeexpand()方法(IE)。这是一个例子。 演示:http://jsfiddle.net/timdown/dBgHn/1/ 代码:
function getWord() {
    var sel, word = "";
    if (window.getSelection && (sel = window.getSelection()).modify) {
        var selectedRange = sel.getRangeAt(0);
        sel.collapseToStart();
        sel.modify("move", "backward", "word");
        sel.modify("extend", "forward", "word");
        
        word = sel.toString();
        
        // Restore selection
        sel.removeAllRanges();
        sel.addRange(selectedRange);
    } else if ( (sel = document.selection) && sel.type != "Control") {
        var range = sel.createRange();
        range.collapse(true);
        range.expand("word");
        word = range.text;
    }
    alert(word);
}

@Tim Down - 有没有办法修改这个函数,使其返回单词边界的位置?即单词的开头和结尾作为数字。例如:检查one tw|o three将返回:[4,7] - ragulka
@TimDown Selection.modify - ragulka
文档说明“单词”的边界是空格字符。但是扩展似乎不适用于URL。有什么想法吗? - Adam Gotterer
神奇!range.expand("word"); 在Chrome中与常规的Range对象一样有效。 - Holtwick
2
还有一件奇怪的事情,它将特殊字符识别为分隔符,而不仅仅是空格。如果一个单词以 @ 开头,比如 @foo,我们得到的单词是 foo,而不是 @foo - SexyBeast
显示剩余9条评论

0

BitBucket发布了他们的Cursores.js库,可以实现这个功能,它很小而且专注,非常好用-http://cursores.bitbucket.org/

我唯一的问题是,如果插入符号左边没有文本,它就无法捕获标记,例如“t|est”可以工作,但“|test”不行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接