美文网首页
<textarea />光标处插入内容笔记

<textarea />光标处插入内容笔记

作者: By_syk | 来源:发表于2016-12-22 15:42 被阅读75次
<textarea />
<div class="form-group">
  <label for="taSource">Source</label>
  <button type="button" id="btTagFrom" class="btn btn-info btn-xs" onclick="insertTag('f')">  [f:]  </button>
  <button type="button" id="btTagUrl" class="btn btn-info btn-xs" onclick="insertTag('u')">  [u:]  </button>
  <button type="button" id="btTagTitle" class="btn btn-info btn-xs" onclick="insertTag('t')">  [t:]  </button>
  <button type="button" id="btTagAuthor" class="btn btn-info btn-xs" onclick="insertTag('a')">  [a:]  </button>
  <button type="button" id="btTagDesc" class="btn btn-info btn-xs" onclick="insertTag('d')">  [d:]  </button>
  <textarea id="taSource" class="form-control" rows="2" style="resize: none"></textarea>
</div>
<script src="<%= request.getContextPath() %>/js/textarea-extra.js" type="text/javascript"></script>
<script type="text/javascript">
  function insertTag(tag) {
    // 取出已输入内容
    var source = $("#taSource").val();
    // 正则匹配避免重复添加
    var regStr = "\\[" + tag + ":.*?\\]";
    if ((new RegExp(regStr)).test(source) != true) {
      // 在光标处插入文字
      $("#taSource").insertContent("[" + tag + ":]");
    }
  }
</script>

textarea-extra.js

// 摘抄自:http://www.jb51.net/article/68490.htm
$(function() {
  /* 在textarea处插入文本--Start */
  (function($) {
    $.fn.extend({
      insertContent : function(myValue, t) {
        var $t = $(this)[0];
        if (document.selection) { // ie
          this.focus();
          var sel = document.selection.createRange();
          sel.text = myValue;
          this.focus();
          sel.moveStart('character', -l);
          var wee = sel.text.length;
          if (arguments.length == 2) {
            var l = $t.value.length;
            sel.moveEnd("character", wee + t);
            t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length)
                : sel.moveStart("character", wee - t - myValue.length);
            sel.select();
          }
        } else if ($t.selectionStart || $t.selectionStart == '0') {
          var startPos = $t.selectionStart;
          var endPos = $t.selectionEnd;
          var scrollTop = $t.scrollTop;
          $t.value = $t.value.substring(0, startPos) + myValue
              + $t.value.substring(endPos, $t.value.length);
          this.focus();
          $t.selectionStart = startPos + myValue.length;
          $t.selectionEnd = startPos + myValue.length;
          $t.scrollTop = scrollTop;
          if (arguments.length == 2) {
            $t.setSelectionRange(startPos - t, $t.selectionEnd + t);
            this.focus();
          }
        } else {
          this.value += myValue;
          this.focus();
        }
      }
    })
  })(jQuery);
  /* 在textarea处插入文本--Ending */
});

相关文章

网友评论

      本文标题:<textarea />光标处插入内容笔记

      本文链接:https://www.haomeiwen.com/subject/njqhvttx.html