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
328 views
in Technique[技术] by (71.8m points)

javascript - Select whole word with getSelection

I want use the getSelection function to select words from articles to a view box.

Here is my code: http://jsfiddle.net/xQKNh/2/.

Now I want to ask, how to use JavaScript to select the whole word?

For explanation,

Is your question about programming?

In my code, if I choose r question about pro, the view box will show

r question about pro

But how to make the words completed? So that it outputs:

your question about programming. 

Javascript code:

function getSelected() {
  if(window.getSelection) { return window.getSelection(); }
  else if(document.getSelection) { return document.getSelection(); }
  else {
    var selection = document.selection && document.selection.createRange();
    if(selection.text) { return selection.text; }
    return false;
  }
  return false;
}
$(document).ready(function() {
  $('#content-area').mouseup(function() {
    var selection = getSelected();
    if(selection && (selection = new String(selection).replace(/^s+|s+$/g,''))) {
        $('#show-text').html(selection)
    }
  });
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Recent versions of Firefox and WebKit browsers have a built-in modify() (see also work-in-progress spec) method of the Selection object to do this. IE has had a completely different way to do this since version 4. In either case, this method has the significant advantage of working across element boundaries.

The following example works in IE 4+, Firefox 4+ and Safari and Chrome in versions released in the last couple of years. Opera as yet has no support for the modify() method of Selection objects.

UPDATE 20 October 2011

I've rewritten this to actually (mostly) work now (it didn't work properly in non-IE browsers before, as pointed out in the comments). Unfortunately, the selection expansion is too greedy in non-IE and expands the selection to the next word if a whole word is already selected, but I can't see an easy way round this at the moment.

UPDATE 11 June 2012

I've now updated this with an improvement from this answer to a related question. Thanks to Matt M and Fong-Wan Chau for this.

Live demo: http://jsfiddle.net/rrvw4/23/

Code:

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);

            var direction = [];
            if (backwards) {
                direction = ['backward', 'forward'];
            } else {
                direction = ['forward', 'backward'];
            }

            sel.modify("move", direction[0], "character");
            sel.modify("move", direction[1], "word");
            sel.extend(endNode, endOffset);
            sel.modify("extend", direction[1], "character");
            sel.modify("extend", direction[0], "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();
        }
    }
}

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

...