Get the word upon which the caret sits within a contenteditable div?

前端 未结 2 1436
醉酒成梦
醉酒成梦 2020-12-17 02:07

I am trying to extract a single word from a content editable div at the position, when the mouse is clicked. For example:

Lorem ipsum dolor sit amet, con

相关标签:
2条回答
  • 2020-12-17 02:54

    You could use the new TextRange module of my Rangy library for this, although it's enormous overkill just for that one feature. Here's the code you'd need:

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

    Otherwise, if you can live with no support for pre-Blink Opera (up to and including version 12) and Firefox < 4, you could use Selection.modify() (WebKit, Firefox) and the expand() method of TextRange (IE). Here's an example.

    Demo: http://jsfiddle.net/timdown/dBgHn/1/

    Code:

    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);
    }
    
    0 讨论(0)
  • 2020-12-17 02:56

    BitBucket have released their Cursores.js library that does this, it's small and focused which is nice - http://cursores.bitbucket.org/

    The only issue I have is that it doesn't pick up the token if there is no text to the left of the caret, for example "t|est" would work but "|test" wouldn't.

    0 讨论(0)
提交回复
热议问题