将光标设置在两个引号之间

时间:2016-04-28 17:10:48

标签: javascript

我有这个textarea,当我点击链接时,插入了2个双引号:

<textarea name="comment" id="comment" placeholder="Comment..."></textarea>
<div id="insert">
 <a href="javascript:;" title='""'>QUOTES</a>
</div>
    <script type="text/javascript" src="jscript.js"></script>
    <script type="text/javascript">
        $('#insert a').click(function () {
   var smiley = $(this).attr('title');
   ins2pos(smiley, 'comment');
});

function ins2pos(str, id) {
   var TextArea = document.getElementById(id);
   var val = TextArea.value;
   var before = val.substring(0, TextArea.selectionStart);
   var after = val.substring(TextArea.selectionEnd, val.length);

   TextArea.value = before + str + after;
   setCursor(TextArea, before.length + str.length);

}

function setCursor(elem, pos) {
   if (elem.setSelectionRange) {
      elem.focus();
      elem.setSelectionRange(pos, pos);
   } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      var posr = pos - 1;
      range.moveEnd('character', posr);
      range.moveStart('character', posr);
      range.select();
   }
}
</script>

当单击QUOTE链接时,光标会跟在textarea中的最后一个字符之后,如""|,但我希望光标位于2个引号之间,如"|"

1 个答案:

答案 0 :(得分:0)

这是解决方案

setCursor(TextArea, before.length + str.length - 1);