How to get selected text in textarea?

This question already has an answer here:

  • How to get selected text from textbox control with javascript 5 answers

  • Try the jquery-fieldselection plugin.

    You can download it from here. There is an example too.


    For obtaining the selected content in a <textarea> with Firefox:

    function getSel() // javascript
    {
        // obtain the object reference for the <textarea>
        var txtarea = document.getElementById("mytextarea");
        // obtain the index of the first selected character
        var start = txtarea.selectionStart;
        // obtain the index of the last selected character
        var finish = txtarea.selectionEnd;
        // obtain the selected text
        var sel = txtarea.value.substring(start, finish);
        // do something with the selected content
    }
    

    window.getSelection().toString() worked for me with Chrome but not Firefox.

    Reference:

  • textarea
  • document

  • Handling selection is different for different browsers:

    var userSelection;
    if (window.getSelection) {
        userSelection = window.getSelection();
    }
    else if (document.selection) { // Opera
        userSelection = document.selection.createRange();
    }
    

    That gives you a range object. Each range represents a single selection (using control/command key it's possible to make multiple active selections).

    The type of range object you have now depends on what browser. For IE it's a Text Range object; for others its a Selection object. To convert a Selection object into a text range, you can call getRangeAt; for Safari, you need to build that:

    var range;
    if (userSelection.getRangeAt)
        range = userSelection.getRangeAt(0);
    else { // Safari
        range = document.createRange();
        range.setStart(userSelection .anchorNode, userSelection.anchorOffset);
        range.setEnd(userSelection.focusNode, userSelection.focusOffset);
    }
    

    The range object provides you with the starting and ending dom elements and text offset of the selection.

    More information about range objects can be found at quirksmode.org here

    If you are using jQuery, you may want to look at the light weight jQuery RTE Plugin by Batiste Bieler. It may do enough for your needs or at least give you something to start with.

    链接地址: http://www.djcxy.com/p/41626.html

    上一篇: 用span展开选定的文本节点

    下一篇: 如何在textarea中获取选定的文本?