【问题标题】:how to get selected text inside a textarea element by javascript?如何通过javascript获取textarea元素内的选定文本?
【发布时间】:2010-11-06 16:20:53
【问题描述】:

我不熟悉这些属性,

谁能提供一个简单的演示?

我需要在没有任何库的情况下完成它。

【问题讨论】:

  • 堆栈溢出存档 - stackoverflow.com/questions/717224/… - stackoverflow.com/questions/275761/… --- 提示:在提问之前,请先查看 Google:site:stackoverflow.com javascript get selected text within textarea 仅返回来自 stackoverflow 的相关材料。 com。或者您可以在地址栏中键入相同的内容,然后是 ?去第一个结果。试一试,在地址栏中输入:?site:stackoverflow.com javascript get selected text within textarea

标签: javascript textarea


【解决方案1】:
<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>

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 2015-04-18
    • 2020-04-21
    • 2012-08-25
    • 2012-12-23
    • 2011-12-10
    • 2011-02-14
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多