<textarea />光标处插入内容笔记
2016-12-22 本文已影响75人
By_syk
<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 */
});