【问题标题】:Get the word upon which the caret sits within a contenteditable div?获取插入符号位于可内容编辑的 div 中的单词?
【发布时间】:2012-06-28 15:18:10
【问题描述】:

单击鼠标时,我正在尝试从该位置的内容可编辑 div 中提取一个单词。例如:

Lorem ipsum dolor sit amet,cons|ectetur adipiscing elit。 Cras 前庭妊娠 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的鼠标点击事件,它计算插入符号的位置,然后找到前后空格字符(或字符串的开头或结尾)的索引,并使用子字符串来确定单词。有一个快速的正则表达式匹配来删除标点符号和空格,我们最终得到了正确的单词。

这很好用,当 contenteditable div 中有一个文本节点时,但是一旦我开始放置和其他各种标签,计算插入符号位置的方法部分就停止工作,总是将其计算为 0 . 有没有办法像处理文本一样计算 HTML 中的插入符号位置?

如果没有,谁能推荐一种替代方法?

【问题讨论】:

标签: javascript html string


【解决方案1】:

您可以为此使用我的 Rangy 库中的新 TextRange module,尽管仅就该功能而言它是巨大的矫枉过正。这是您需要的代码:

var sel = rangy.getSelection();
sel.expand("word");
var word = sel.text();
alert(word);

否则,如果您可以忍受不支持 pre-Blink Opera(直到并包括版本 12)和 Firefox Selection.modify()(WebKit、Firefox)和 @987654329 的 expand() 方法@ (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:哪个版本? Rangy 还是Selection.modify()
  • @TimDown Selection.modify
  • @ragulka:你可以把它和这个函数结合起来:stackoverflow.com/a/4812022/96100
  • 还有一个奇怪的地方,它把特殊字符识别为分隔符,而不仅仅是空格。如果一个词以@ 开头,比如@foo,我们得到的词是foo,而不是@foo
【解决方案2】:

BitBucket 已经发布了他们的 Cursores.js 库,它可以做到这一点,它小巧而专注,这很好 - http://cursores.bitbucket.org/

我遇到的唯一问题是,如果插入符号左侧没有文本,它不会拾取令牌,例如“t|est”可以工作,但“|test”不会。

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 2011-04-27
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2013-04-24
    • 2020-07-24
    相关资源
    最近更新 更多