在光标位置插入笑脸 [英] Insert smiley at cursor position

查看:122
本文介绍了在光标位置插入笑脸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个项目,用户可以点击表情符号,并将其插入contenteditable div。

I am making a project where users can click on the smileys and they get inserted in contenteditable div.


  1. 我想要三个div在任何div,我的笑脸应该插入那个div。

  2. 此外,这里的问题是表情只插入div的结尾。我想要笑脸应该只输入光标的任何地方。

注意:请检查所有div中的表情大小是否相同。

<div id="text_wrapper">
    <div id="text" contentEditable="true" hidefocus="true"></div>
</div>
<div id="text_wrapper">
   <div id="text1" contentEditable="true" hidefocus="true"></div>
</div>
<div id="text_wrapper">
   <div id="text2" contentEditable="true" hidefocus="true"></div>
</div>
<span id="button">Add Emoji</span>







$("#button").click(function() {
  $("#text").append('<img src="https://cdn.okccdn.com/media/img/emojis/apple/1F60C.png"/>');
});


演示

推荐答案

第一:插入正确的三个元素之一

您正在使用表达式 #text 它指的是第一个可编辑的div。

You are using the expression #text which refers to the first editable div.

如果你想定位最后一个焦点的对象,你可以使用类

If You'd like to target the one with the last focus on it, You can use classes for this.

向他们添加类,以便您可以轻松定位其中任何一个。

Add a class to them, so You can easily target any of them

<div id="text_wrapper">

    <div id="text" class="editable" contentEditable="true" hidefocus="true"></div>

</div>

<div id="text_wrapper">

   <div id="text1" class="editable" contentEditable="true" hidefocus="true"></div>

</div>

<div id="text_wrapper">

   <div id="text2" class="editable" contentEditable="true" hidefocus="true"></div>

</div>

<span id="button">Add Emoji</span>

然后,您可以轻松决定单一事件监听器的焦点位置。

Then You can easily decide where the focus is with a single event listener

$( document ).on( "click focusin" , ".editable" , function(){

    $( ".editable" ).removeClass( "focus" );
    $( this ).addClass( "focus" );

} );



从这一点开始,焦点项(带有光标的项)将具有类.focus 。

From this point, the focused item ( the one with the cursor ) will have the class ".focus".

现在,您可以使用

$( document ).on( "click" , "#button" , function() {

  $( ".editable.focus" ).append( '<img src="https://cdn.okccdn.com/media/img/emojis/apple/1F60C.png"/>' );

});



第二:在光标位置插入

这似乎有点复杂,但有很干净的方法。请查看此主题

This seems to be a bit more complex, but there are pretty clean ways. Take a look at this topic.

这篇关于在光标位置插入笑脸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆