返回列表

textarea,input 输入框获取光标位置,在光标处插入文字,替换选中文字, 获取选中文字

默认分类 2018/07/24 09:53

Demo地址:http://haiyang.me/upload/input-cursor.html

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>haiyang.me &gt; input输入框获取光标位置,在光标处插入文字,替换选中文字</title>
  <script>
  //获取光标位置函数
  function getCursorPosition(elem) {
    var pp = 0
    // IE
    if (document.selection) {
      elem.focus()
      var aa = document.selection.createRange()
      aa.moveStart('character', -elem.value.length)
      pp = aa.text.length
    }
    // FF, Chrome
    else if (elem.selectionStart || elem.selectionStart == '0') {
      pp = elem.selectionStart
    }
    return pp
  }
  //设置光标位置函数
  function setCaretPosition(elem, pos) {
    // IE
    if (elem.setSelectionRange) {
      elem.focus()
      elem.setSelectionRange(pos, pos)
    }
    // FF, Chrome
    else if (elem.createTextRange) {
      var range = elem.createTextRange()
      range.collapse(true)
      range.moveEnd('character', pos)
      range.moveStart('character', pos)
      range.select()
    }
  }
  function insertAtCursor(elem, value) {
    var field = elem
    var newValue = ''
    // IE support
    if (document.selection) {
      field.focus()
      var sel = document.selection.createRange()
      sel.text = newValue = value
      sel.select()
    } else if (field.selectionStart || field.selectionStart === 0) {
      var startPos = field.selectionStart
      var endPos = field.selectionEnd
      var restoreTop = field.scrollTop
      newValue = field.value.substring(0, startPos) +
        value +
        field.value.substring(endPos, field.value.length)
      if (restoreTop > 0) {
        field.scrollTop = restoreTop
      }
      field.value = newValue
      field.focus()
      setTimeout(function() {
        field.selectionStart = startPos + value.length
        field.selectionEnd = startPos + value.length
      }, 0)
    } else {
      newValue = field.value + value
      field.value = newValue
      field.focus()
    }
  }
  </script>
</head>
<body>
  <input id="a" type=text name=text1 value="1234567890">
  <button onclick="alert(getCursorPosition(a))">获取光标位置</bottun>
  <button onclick="setCaretPosition(a, 5)">设置光标位置: 5</bottun>
  <button onclick="insertAtCursor(a, 'ww')">替换或插入文字: ww</bottun>
</body>
</html>