How to select text with jQuery

2019-02-19 02:57发布

问题:

How can I select a part of the text and process by jQuery? For example, I have a text as

<div id="test">This is an example text here</div>

I select few words (not the whole div) with mouse, and want to show these words (part of #test) in

<div id="target"></div>

回答1:

Here's how. The following works in all major browsers, including IE 6.

function getSelectedText() {
    var selectedText = "", sel;
    if (window.getSelection) {
        selectedText = "" + window.getSelection();
    } else if ( (sel = document.selection) && sel.type == "Text") {
        selectedText = sel.createRange().text;
    }
    return selectedText;
}

$('#target').text( getSelectedText() );


回答2:

If you mean by select text then show it into an element.

var selectedText;

if(window.getSelection)
{
    selectedText = window.getSelection();
}
else if(document.getSelection)
{
    selectedText = document.getSelection();
}
else if(document.selection)
{
    selectedText = document.selection.createRange();
}

$('#target').text(selectedText.toString());

Or by typical showing an element text into another element, then you use:

$('#target').text($('#test').text());


回答3:

You can use the text method like so:

(function(namespace) {
  namespace.getSelected = function() {
    var t = '';
    if (window.getSelection) {
        t = window.getSelection();
    } else if (document.getSelection) {
        t = document.getSelection();
    } else if (document.selection) {
        t = document.selection.createRange().text;
    }
    return t;
  };
}(Namespace || {}))

$(function() {
  $('#test').on("mouseup", function() {
    var selectedText = Namespace.getSelected();
    if (selectedText) {
      $('#target').text(selectedText);
    }
  });
});


回答4:

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if(this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

Reference: http://programanddesign.com/js/jquery-select-text-range/



回答5:

You would have to use http://www.examplet.buss.hk/jquery/caret.php plugin and you could easily get the selected text

// Get start pos in intput box with id="box1" $("#box1").caret().start

// Get end pos $("#box1").caret().end

// Get selected text $("#box1").caret().text



回答6:

Please refer

http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html