how to get selected text inside a textarea element by javascript?

后端 未结 1 902
情深已故
情深已故 2020-12-18 15:15

I\'m not familiar with such attributes,

can someone provide a simple demo?

I need it to be done without any libraries.

相关标签:
1条回答
  • 2020-12-18 15:25
    <script type="text/javascript">
    
            function ShowSelectionInsideTextarea()
    {
     var textComponent = document.getElementById('mytextarea');
    
      var selectedText;
      // IE version
      if (document.selection != undefined)
      {
        textComponent.focus();
        var sel = document.selection.createRange();
        selectedText = sel.text;
      }
      // Mozilla version
      else if (textComponent.selectionStart != undefined)
      {
        var startPos = textComponent.selectionStart;
        var endPos = textComponent.selectionEnd;
        selectedText = textComponent.value.substring(startPos, endPos)
      }
        alert("You selected: " + selectedText);
    
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题