在textarea里实现获取光标位置和选中内容

在我们的service后台,使用jQuery写了一个微信聊天的网页版,嵌在了我们的后台系统里,如下图所示:

今天临时加了一个这样的优化,在输入框里复制粘贴过一段文字过来之后,运营要直接在输入框里排版,既可以使用Alt+Enter实现回车,又可以在中间插入表情。然后我发现了selectionStart和selectionEnd这两个方法自己先写了一个小demo来实现
     获取光标的下标,

    滑动的时候获取开始结束的位置及选中内容等等,

当然还有强制让光标显示在某个下标位置使用obj.selectionStart= obj.selectionEnd =5;等等,发现了一些有意思的功能。

    

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    #dope{
         200px;
        height: 400px;
    }
    </style>
</head>
<body>
    <textarea id="dope">
    </textarea>
    <div id="getSelectedText">hahahhahahah</div>
</body>
</html>

<script>
    window.onload = function() {

      var textarea = document.getElementById('dope');
      var getPosi = document.getElementById('getSelectedText');

      getPosi.onclick = function () {
        console.log(getSelectedText(textarea))
      }

      function getSelectedText(obj) {
        var userSelection;
        if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
          // 非IE浏览器
          var startPos = obj.selectionStart,// 获取选区的开始位置
              endPos = obj.selectionEnd;// 获取选区的结束位置
          console.log("非IE:")
          console.log("选区开始点:" + startPos + ',选区结束点:' + endPos)

          userSelection = obj.value.substring(startPos, endPos)
        } else if (document.selection) {
          // IE浏览器
          console.log("IE:")
          userSelection = document.selection.createRange().text
        }
        return userSelection
      }
    }
</script>

  

原文地址:https://www.cnblogs.com/katydids/p/11312354.html