将文本插入光标所在的文本区域(不附加到末尾)

时间:2018-02-01 20:15:46

标签: jquery

所以,我有一个textarea,我想通过点击按钮添加文字。

但是,当我这样做时,它会附加到框的末尾而不是光标所在的位置。我怎样才能做到这一点?

JS小提琴:https://jsfiddle.net/ukLaz8cm/127/



$(document).ready(function() {
  $("#emojionearea1").emojioneArea({

    pickerPosition: "right",
    tonesStyle: "bullet",
    events: {
      keyup: function(editor, event) {
        console.log(editor.html());
        console.log(this.getText());
      }
    }
  });
});

$('.aClass').click(function(e) {
  e.preventDefault(); //to prevent the default behaviour of a tag 
  var val = $('#emojionearea1').data("emojioneArea").getText(); //get prvious value
  if ($(this).text() == 'Test 1') {
    $('#emojionearea1').data("emojioneArea").setText(val + "\r\n" + 'Thank You');
  } else {
    $('#emojionearea1').data("emojioneArea").setText(val + "\r\n" + 'Good Luck');
  }
});

* {
  font-family: Arial, Helvetica, san-serif;
}

.row:after,
.row:before {
  content: " ";
  display: table;
  clear: both;
}

.span6 {
  float: left;
  width: 48%;
  padding: 1%;
}

.emojionearea-standalone {
  float: right;
}

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//rawgit.com/mervick/emojionearea/master/dist/emojionearea.js"></script>

<link href="https://rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.css" rel="stylesheet" type="text/css" />  

<a href="#" class="aClass" data-text="Thank You">Test 1</a> Clicking this will add "Thank you" to textarea<br/>
<a href="#" class="aClass" data-text="Good Luck">Test 2</a> Clicking this will add "Good luck" to textarea<br/>

<div class="row">
  <div class="span6">
    <textarea id="emojionearea1"></textarea>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:-1)

您正在设置整个文本区域的文本。

查看此Inserting a text where cursor is using Javascript/jquery