簡體   English   中英

JavaScript:當用戶按回車鍵且插入符號位於 html 節點內時,如何正確處理 contenteditable 中的內容中斷?

[英]JavaScript: How to correctly handle content break in contenteditable when user hits enter and caret is within html nodes?

我正在開發一個簡單的塊編輯器系統,當用戶在塊中間點擊輸入時,我正在努力移動/設置塊之間的內容。 假設我有這個可編輯的 div,插入符號顯示為“|” 以下:

<p contenteditable="true">this is my <strong><em>content |with</em> some styles</strong></p>

如果我按回車鍵,我想實現這一點:

<p contenteditable="true">this is my <strong><em>content </em></strong></p>
<p contenteditable="true"><strong><em>with</em> some styles</strong></p>

更准確地說,我已經在處理節點創建(例如上面的輸入鍵上的p標簽)。

當用戶點擊進入時,我正在努力處理內容本身,並且 cursor 在 html 節點內。 在這里,插入符號位於strongem節點內。 我發現很難(1)確定它的確切 position 如果像上面那樣涉及多個 HTML 子節點,並且(2)相應地拆分內部內容(“這是我的某些樣式的內容”)並重新分配<strong><em>標簽,它們在邏輯上應該在兩行上。

此外,有多個contenteditable元素是有目的的,也是當前的限制。

非常感謝純 JavaScript 中的一些指導。 謝謝!

如果有人遇到同樣的問題,我是這樣解決的:

// START: Somewhere in my code
const wrapper = document.querySelector('.wrapper') // Content wrapper
wrapper.addEventListener('keydown', handleKeyDown)

const handleKeyDown = (e) => {
  if (e.keyCode === 13) { // User hits enter
    e.preventDefault() // cancel enter
    // ... other logic
    splitContent(e.target) // call my method to split content if required
  }
}
// END: Somewhere in my code

// the method that solved my issue, using Range and Selection objects
const splitContent = (node) => {
  const range = window.getSelection().getRangeAt(0)
  // Select the end node and its offset from the caret
  range.setStart(range.endContainer, range.endOffset);
  // End the selected range at the end of the node content 
  range.setEnd(node, node.childNodes.length) 
  // Extract content from the defined range (the key is here)
  const content = range.extractContents() 
  // Call another method to use this extracted content with formatting intact
  doWhateverWithTheExtractedContent(content)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM