在contenteditable編輯器中優雅處理Shift+Enter換行
使用contenteditable=”true”的編輯器時,Shift+Enter換行常常導致內容結構混亂。本文提供一個解決方案,確保換行操作不會破壞編輯器的格式。
問題:Shift+Enter換行導致結構混亂
在可編輯區域(例如,contenteditable=”true”的div元素)中,直接使用Shift+Enter換行,瀏覽器默認行為可能會插入
標簽,導致內容結構混亂,尤其在需要段落級格式化時。
以下是一個示例代碼,展示了這個問題:
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #editable { width: 300px; height: 300px; border: 1px solid #ccc; padding: 10px; } </style> <div contenteditable="true" id="editable" oninput="inputText()" onkeydown="keyDown(event)"></div> <script> function keyDown(event) { document.execCommand('formatblock', false, '<p>'); } function inputText() { // 用于調試,查看當前元素的innerHTML if (document.getSelection().focusNode.data !== undefined) { var currentElement = document.getSelection().focusNode.parentNode; console.log(currentElement.innerHTML); } } </script>
解決方案:使用insertParagraph命令
通過修改keyDown函數,我們可以攔截Shift+Enter組合鍵,并使用document.execCommand(‘insertParagraph’)插入一個新的段落,從而避免結構混亂。
改進后的keyDown函數如下:
function keyDown(event) { if (event.shiftKey && event.keyCode === 13) { event.preventDefault(); // 阻止默認行為 document.execCommand('insertParagraph'); return false; // 阻止事件冒泡 } document.execCommand('formatblock', false, '<p>'); }
此解決方案已在chrome 120.0.6099.201 (Official Build) (64-bit)版本上測試通過,有效地解決了Shift+Enter換行導致的結構混亂問題,保證了編輯內容的格式整潔。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END