簡體   English   中英

Javascript RTF編輯器,單擊按鈕后,內容可編輯區域失去焦點

[英]Javascript rich text editor, contenteditable area loses focus after button is clicked

我有簡單的javascript RTF編輯器,僅包含具有以下onclick的粗體按鈕:

  document.execCommand('bold', false)

和簡單的html ...

<div contenteditable="true">

我的問題是,當我單擊粗體按鈕時,文本區域失去了焦點,是否有解決方案?

好吧,焦點移到了按鈕上,因此您需要取消單擊操作,以使焦點不會丟失到內容可編輯元素中。

 document.querySelector(".actions").addEventListener("mousedown", function (e) { var action = e.target.dataset.action; if (action) { document.execCommand(action, false) //prevent button from actually getting focused e.preventDefault(); } }) 
 [contenteditable] { width: 300px; height: 300px; border: 1px solid black; } 
 <div class="actions"> <button data-action="bold">bold</button> <button data-action="italic">italic</button> </div> <div contenteditable="true"></div> 

答案更新

查看此答案,您可以保存和還原當前contenteditable的位置,將blur事件偵聽器添加到contenteditable

一個例子:

 // // restore position after click // document.getElementById('btn').addEventListener('click', function(e) { restoreSelection(cpos); }) // // save position on blur // document.querySelector('div[contenteditable="true"]').addEventListener('blur', function(e) { cpos = saveSelection(); }) function saveSelection() { if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { return sel.getRangeAt(0); } } else if (document.selection && document.selection.createRange) { return document.selection.createRange(); } return null; } function restoreSelection(range) { if (range) { if (window.getSelection) { sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (document.selection && range.select) { range.select(); } } } var cpos = -1; 
 <button id="btn">Make bold</button> <div contenteditable="true"> this is the text </div> 

暫無
暫無

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

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