Get selected text in a textbox

后端 未结 3 1184
太阳男子
太阳男子 2020-12-19 02:28

How can I get the character positions of the selected text in an HTML textbox element? window.getSelection() doesn\'t work inside tex

相关标签:
3条回答
  • 2020-12-19 03:18

    ........

    <script language=javascript>
    function getSelText()
    {
        var txt = '';
         if (window.getSelection)
        {
            txt = window.getSelection();
                 }
        else if (document.getSelection)
        {
            txt = document.getSelection();
                }
        else if (document.selection)
        {
            txt = document.selection.createRange().text;
                }
        else return;
    document.aform.selectedtext.value =  txt;
    }
    </script>
    
    <input type="button" value="Get selection" onmousedown="getSelText()"> 
    
    <form name=aform >
    <textarea name="selectedtext" rows="5" cols="20"></textarea>
    </form>
    

    Reference: http://www.codetoad.com/javascript_get_selected_text.asp

    0 讨论(0)
  • 2020-12-19 03:24

    If you're using jQuery, take a look at the jQuery Caret plugin: jCaret

    // Get start pos in intput box with id="box1"
    $("#box1").caret().start
    
    // Get end pos
    $("#box1").caret().end
    
    // Get selected text
    $("#box1").caret().text
    
    0 讨论(0)
  • 2020-12-19 03:24

    In case you don't need to support really old versions of Internet Explorer, just use the element's selectionEnd and selectionStart properties.

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