smilies to textarea on click

后端 未结 4 997
盖世英雄少女心
盖世英雄少女心 2021-01-06 07:21

I have a little question

I want to click on my smileys and insert the text to the textarea. and when I want to add a smiley later, the smiley should be added to the

4条回答
  •  余生分开走
    2021-01-06 07:48

    Also, you can use something this function:

    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;
    }
    

    For your example, look here.


    UPD 1:

    To set cursor at specified position, use the next function:

    function setCursor(elem, pos) {
       if (elem.setSelectionRange) {
          elem.focus();
          elem.setSelectionRange(pos, pos);
       } else if (elem.createTextRange) {
          var range = elem.createTextRange();
          range.collapse(true);
          range.moveEnd('character', pos);
          range.moveStart('character', pos);
          range.select();
       }
    }
    

    I updated code on jsFiddle, so, to view new example, look here.

提交回复
热议问题