简体   繁体   English

如何在 contentEditable div 的字母之间添加表情符号?

[英]how to add emoji in between the letters in contentEditable div?

I want to add smiles to the div but problem is it is not adding in between two letters or when I point my cursor in between it is adding at last please help.I want to add the emoji in between.我想在 div 中添加微笑,但问题是它没有在两个字母之间添加,或者当我将光标指向它之间时,它最后添加了请帮忙。我想在它们之间添加表情符号。

    <!DOCTYPE html>
    <head>

    <style type="text/css">


    #text {  body {
      font-family: Helvetica, sans-serif;
      color: #333;
    }
    #text_wrapper {
      margin: 40px;

    }
      outline: none;
      margin: 10px;
      min-height:200px;
    }




    </style>
    </head>
    <html>
    <body>
    <script>
    function myFunction() {
        var x = document.createElement("IMG");
        x.setAttribute("src", "1f602.png");
        x.setAttribute("width", "20");
        document.body.appendChild(x);
        var c=document.getElementById("text"); 
        c.appendChild(x);
    }

    </script>
    <div id="text" contentEditable="true" >


    </div>
    <button onclick="myFunction()"  >Emoji </button>
    </body>
    </html>

I've made a working example based on @tim-down 's perfect answer, and it's working very well:我已经根据@tim-down的完美答案制作了一个工作示例,并且效果很好:

 function pasteHtmlAtCaret(html) { let sel, range; if (window.getSelection) { // IE9 and non-IE sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); // Range.createContextualFragment() would be useful here but is // non-standard and not supported in all browsers (IE9, for one) const el = document.createElement("div"); el.innerHTML = html; let frag = document.createDocumentFragment(), node, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } else if (document.selection && document.selection.type != "Control") { // IE < 9 document.selection.createRange().pasteHTML(html); } } function addToDiv(event) { const emoji = event.target.value; const chatBox = document.getElementById("chatbox"); chatBox.focus(); pasteHtmlAtCaret(`<b>${emoji}</b>`); } function generateEmojiIcon(emoji) { const input = document.createElement("input"); input.type = "button"; input.value = emoji; input.innerText = emoji; input.addEventListener("click", addToDiv); return input; } const emojis = [ { emoji: "😂", }, { emoji: "❤️", }, ]; emojis.forEach((emoji) => { document .getElementById("emojis") .appendChild(generateEmojiIcon(emoji.emoji)); });
 #emojis span { cursor: pointer; } #chatbox { border: 1px solid; }
 <button type="button" onclick="document.getElementById('chatbox').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); " > Paste HTML </button> <div id="emojis"></div> <div id="chatbox" contenteditable></div>

You need to get the position of the cursor, after that, you need to insert the image at that point.您需要获取光标的位置,之后,您需要在该点插入图像。 Something like this would work:像这样的事情会起作用:

function getCaretCharacterOffsetWithin(element) {
    var caretOffset = 0;
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
            var range = win.getSelection().getRangeAt(0);
            var preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        var textRange = sel.createRange();
        var preCaretTextRange = doc.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
}

function myFunction() {
        var c=document.getElementById("text"); 
        var position = getCaretCharacterOffsetWithin(c);
        var text = c.innerHTML;
        var imgStr = '<img src="1f602.png" width="20" />'
        c.innerHTML = text.slice(0,position) + imgStr + text.slice(position,text.length);
    }

See it working here: https://jsfiddle.net/br9yg1bk/看到它在这里工作: https : //jsfiddle.net/br9yg1bk/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 VueJS:如何将emoji表情组件动态嵌入到contentEditable div中 - VueJS: How to embed the emoji component dynamically in contentEditable div 在contenteditable中将光标设置在2个字母之间 - set cursor between 2 letters in contenteditable 如何在javascript中将新行添加到div中? - How to add New line to a div contenteditable in javascript? 如何使用&#39;contenteditable&#39;属性将keypress事件添加到div - How to add keypress event to div with 'contenteditable' attribute 如何在没有contentEditable的`div`上添加键盘事件 - How to add keyboard event on `div` without contentEditable 按条件着色在contenteditable div textfield中的字母 - Colorize letters in contenteditable div textfield by condition 在 contenteditable div 中按回车键时如何添加新 div - How to add new div when hitting enter key in contenteditable div 在PHP中使用jQuery Ajax在第一个contenteditable div超过高度后如何添加新的contenteditable div? - How to add new contenteditable div after first contenteditable div exceed the height using jquery ajax in php? HPW仅允许将表情符号图像用于内容可编辑的div粘贴 - Hpw to allow only emoji images for contenteditable div on paste and drop 如何将一个类添加到在contenteditable元素内创建的div中? - How to add a class to a div created inside a contenteditable element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM