Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

html - How do I extend selection to word boundary using JavaScript, once only?

I'm using the technique shown in this answer to extend a web page's selection to a word boundary:

function snapSelectionToWord() {
    var sel;

    // Check for existence of window.getSelection() and that it has a
    // modify() method. IE 9 has both selection APIs but no modify() method.
    if (window.getSelection && (sel = window.getSelection()).modify) {
        sel = window.getSelection();
        if (!sel.isCollapsed) {

            // Detect if selection is backwards
            var range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);
            var backwards = range.collapsed;
            range.detach();

            // modify() works on the focus of the selection
            var endNode = sel.focusNode, endOffset = sel.focusOffset;
            sel.collapse(sel.anchorNode, sel.anchorOffset);
            if (backwards) {
                sel.modify("move", "forward", "word");
                sel.extend(endNode, endOffset);
                sel.modify("extend", "backward", "word");

            } else {
                sel.modify("move", "backward", "word");
                sel.extend(endNode, endOffset);
                sel.modify("extend", "forward", "word");
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        var textRange = sel.createRange();
        if (textRange.text) {
            textRange.expand("word");
            // Move the end back to not include the word's trailing space(s),
            // if necessary
            while (/s$/.test(textRange.text)) {
                textRange.moveEnd("character", -1);
            }
            textRange.select();
        }
    }
}?

So far, so good. But if you call the snapSelectionToWord function more than once on the selection, it's expanded outward by one word in both directions on each call, which is not good if you want to call it more than once while text is selected.

Here's a live jsFiddle example that allows you to repeatedly click a 'Snap' button, which demonstrates the problem.

How can the original solution be fixed so that it doesn't expand the selection if it's already on a word boundary?

  • I'd prefer to leave a comment on the original solution but, sadly, I've not yet been graced with sufficient karma by the StackOverflow karma brigade--otherwise, I'd just ask there. And I'm not sure how to fix the problem, so I won't edit the original solution.

Edit: Adding code snippet per request

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wrote that sample. I've never been happy with it, for the reason you point out, and also because it doesn't work consistently in all browsers (or at all in Opera).

I've been working on a cross-browser solution to this for my Rangy library. The current release is described as an alpha but it works pretty well. Here's a demo:

http://rangy.googlecode.com/svn/trunk/demos/textrange.html

And here's your demo, modified to use Rangy:

http://jsfiddle.net/timdown/RgZ8r/

The crucial line is

rangy.getSelection().expand("word");

If you don't want to use something as heavyweight as Rangy (it's something like 50KB of code to use the TextRange module) then it's possible to improve the original code (as Matt M has in his answer) but it will still have limitations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...