JavaScript获取文本框内选中的文本

JavaScript获取文本框内选中的文本

 

 

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #a{
      background: #39bcb8;
      color: white;
    }
    #btn{
      background: #af9ca4;
      color: white;
    }
  </style>
</head>
<body>
<textarea id="a" rows="3" cols="20">在输入框里的内容里面:选择我,然后点击下面的按钮</textarea><br />
<button id="btn" onclick="alert(getFieldSelection(document.getElementById('a')))">button_click</button>
<br />
</body>
</html>
<script type="text/javascript">
  function getFieldSelection(select_field)
  {
    word='';
    if (document.selection) {
      var sel = document.selection.createRange();
      if (sel.text.length > 0) {
        word = sel.text;
      }
    }
    else if (select_field.selectionStart || select_field.selectionStart == '0') {
      var startP = select_field.selectionStart;
      var endP = select_field.selectionEnd;
      if (startP != endP) {
        word = select_field.value.substring(startP, endP);
      }
    }
    return word;
  }
</script>
代码实现

 

posted @ 2019-09-21 09:36  Mahmud(مەھمۇد)  阅读(240)  评论(0编辑  收藏  举报