html 富文本编辑器相关--输出选中文字和主动选择文字
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="app" contenteditable="true"> <span id="content">12345675345</span> <p id="content2">12345675345</p> </div> <button id="btn">显示选中文字</button> </body> <script> selction = window.getSelection(); const btn = document.querySelector('#btn'); const app = document.querySelector('.app'); const content = document.querySelector('#content'); const content2 = document.querySelector('#content2'); app.focus(); btn.onclick = function () { let selction ,text; console.log(selction.toString());//输出选中文字 alert(selction); } let range = selction.getRangeAt(0); range.setStart(selction.anchorNode,selction.anchorOffset); range.setEnd(selction.focusNode,selction.focusOffset+6); selction.removeAllRanges(); selction.addRange(range);//主动添加选中文字 console.log(selction); </script> </html>