Backspace doesn't delete inner html tags of a contenteditable DIV in Firefox
I have created a DIV with attribute contenteditable=true
and appended children like span
and a
with attributes contenteditable=false
.
Wanted to test if the entire node be deleted with a single backspace and to my surprise Firefox couldn't delete the elements.
Also, t开发者_开发知识库his works as expected in all major desktop browsers except Firefox.
Any clues on this or what could be the possible workaround?Found the exact issue on bugzilla here.
Okay! found the solution... its rather simple than what you would think. I am actually inserting html for links, so using <a>
here. The <a>
tag has attribute set to contenteditable=false and its not getting deleted with a backspace. So I have created an inner <span>
level with contenteditable=true for firefox and that did the trick.
<div contentEditable="true">
<a href="your/url/path" contentEditable="false">
<span contentEditable="true">link here</span>
</a>
</div>
This is required in Firefox only. Other browsers treat this as expected with the span having content contenteditable=false.
I have faces the same terrible bug and had no choice but to make an elaborate javascript-based solution that listens to keypress events and if backspace was pressed, and the caret was just at the start offset of a text node, and the node before it is an element node, then delete that whole element node.
// credit: https://stackoverflow.com/a/25397485/104380
var isFF = !!navigator.userAgent.match(/firefox/i)
var editableElm = document.querySelector('div')
// listen to any key press
if( isFF )
editableElm.addEventListener('keydown', onKeydown)
function onKeydown(e){
if( e.key == "Backspace" ){
var selection = document.getSelection();
// if caret is at the begining of the text node (0), remove previous element
if( selection && selection.anchorOffset == 0 )
selection.anchorNode.previousSibling.parentNode.removeChild(selection.anchorNode.previousSibling)
}
}
<div contenteditable='true'>
Try deleting theme <mark contenteditable='false'>marked</mark> words on <mark contenteditable='false'>Firefox</mark> ok?
</div>
Try adding an "onkeydown" function on the editable div to stop event propagation (as follows). Worked for me:
onKeyDown = (e) => { e.stopPropagation(); }
精彩评论