巧妙解決contenteditable=”true”編輯框中Shift+Enter換行難題
使用contenteditable=”true”的編輯框時(shí),Shift+Enter鍵的換行處理常常導(dǎo)致內(nèi)容結(jié)構(gòu)混亂。 用戶期望Shift+Enter插入新段落,但默認(rèn)行為卻可能造成格式錯(cuò)誤。本文提供JavaScript解決方案,確保編輯框內(nèi)容結(jié)構(gòu)整潔有序。
以下html代碼包含一個(gè)contenteditable=”true”的div元素,通過onkeydown和oninput事件監(jiān)聽用戶輸入和鍵盤操作:
<meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <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) { if (event.shiftKey && event.keyCode === 13) { event.preventDefault(); document.execCommand('insertParagraph'); return false; } document.execCommand('formatblock', false, '<p>'); } function inputText() { if (document.getSelection().focusNode.data !== undefined) { const currentElement = document.getSelection().focusNode.parentNode; console.log(currentElement.innerHTML); } } </script>
keyDown函數(shù)是關(guān)鍵。它檢測用戶是否按下Shift+Enter ( event.shiftKey && event.keyCode === 13 )。 如果是,則使用event.preventDefault()阻止默認(rèn)行為,并調(diào)用document.execCommand(‘insertParagraph’)插入新段落,從而避免結(jié)構(gòu)混亂。
需要注意的是,此方案已在chrome 120.0.6099.201 (Official Build) (64-bit) (cohort: Control) 版本中測試通過。其他瀏覽器可能需要調(diào)整代碼以保證兼容性。 inputText函數(shù)用于演示如何獲取當(dāng)前選中文本的父元素內(nèi)容,方便調(diào)試和進(jìn)一步的處理。
立即學(xué)習(xí)“Java免費(fèi)學(xué)習(xí)筆記(深入)”;