在制作富文本编辑器,尤其是在制作以div元素为编辑器区域时,当鼠标离开编辑区域以后会失去焦点,失去选区,这时候就要通过selection&range来重新设置选区。【以下代码尚未考虑IE低版本,请在现代浏览器下测试学习】
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>range</title> <style type="text/css"> #edit{ width: 100%; height: 300px; border: 1px solid #ccc; } </style> </head> <body> <div contenteditable="true" id="edit"> <p>通过一个富文本编辑器,学习JavaScript!</p> </div> <div id="button">button</div> <script type="text/javascript"> var edit = document.getElementById(‘edit‘); var button = document.getElementById(‘button‘); edit.addEventListener(‘mouseup‘, function() { saveSelection(); }); button.addEventListener(‘click‘, function() { restoreSelection(); document.execCommand(‘underline‘, false, null); saveSelection(); }); function saveSelection() { selection = document.getSelection(); save = selection.getRangeAt(0); } function restoreSelection() { var selection = window.getSelection(); if(selection.rangeCount > 0) { selection.removeAllRanges(); } var range = document.createRange(); selection.addRange(save); } </script> </body> </html>
时间: 2024-11-13 09:26:08