一、insertNode
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .edit { width: 400px; height: 140px; border: 2px solid #ff7f50; overflow: auto } </style> </head> <body> <div class="emoji-container"> </div> <div class="edit" contenteditable="true"> </div> <script> const arr = [‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘] let container = document.querySelector(‘.emoji-container‘) let html = `` for (let i = 0; i < arr.length; i++) { html += `<span>${arr[i]}</span>` } let edit = document.querySelector(‘.edit‘) let range edit.onclick = function() { range = window.getSelection().getRangeAt(0) } edit.oninput = function() { range = window.getSelection().getRangeAt(0) } container.innerHTML = html let emojis = document.querySelectorAll(‘span‘) for (let i = 0; i < emojis.length; i++) { emojis[i].onclick = function() { let newNode = document.createElement(‘span‘) newNode.innerText = this.innerText range.insertNode(newNode) console.log(range); } } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .edit { width: 400px; height: 140px; border: 2px solid #ff7f50; overflow: auto } </style> </head> <body> <div class="emoji-container"> </div> <div class="edit" contenteditable="true"> </div> <script> const arr = [‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘, ‘??‘] let container = document.querySelector(‘.emoji-container‘) let html = `` for (let i = 0; i < arr.length; i++) { html += `<span>${arr[i]}</span>` } let edit = document.querySelector(‘.edit‘) let range edit.onclick = function() { range = window.getSelection().getRangeAt(0) } edit.oninput = function() { range = window.getSelection().getRangeAt(0) // editF(edit.innerHTML) } container.innerHTML = html let emojis = document.querySelectorAll(‘span‘) for (let i = 0; i < emojis.length; i++) { emojis[i].onclick = function() { let newNode = document.createElement(‘span‘) newNode.innerText = this.innerText range.collapse() range.insertNode(newNode) } } </script> </body> </html>
以上案例来自于李同学~
原文:https://www.cnblogs.com/yiyi17/p/9619570.html