Backspace doesn't delete inner html tags of a contenteditable DIV in Firefox

后端 未结 2 1032
日久生厌
日久生厌 2021-01-05 13:47

I have created a DIV with attribute contenteditable=true and appended children like span and a with attributes contenteditable=f

相关标签:
2条回答
  • 2021-01-05 13:57

    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.

    0 讨论(0)
  • 2021-01-05 13:59

    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>

    0 讨论(0)
提交回复
热议问题