代码之家  ›  专栏  ›  技术社区  ›  Tobi

Contenteditable:如何在按del或backspace时完全删除span

  •  11
  • Tobi  · 技术社区  · 7 年前

    我有一个 contenteditable div,如下面的HTML所示(插入符号由 |

    我想删除 span.label 按下时 退格 Name 在一次按键中被删除)

    <div contenteditable="true">
       Hallo, <span class="label">Name</span>|,
       this is a demonstration of placeholders!
       Sincerly, your
       <span class="label">Author</span>
    </div>
    
    2 回复  |  直到 7 年前
        1
  •  16
  •   Dekel    7 年前

    您需要检查光标是否位于跨度末端的准确位置,如果是,请将其删除:

    document.querySelector('div').addEventListener('keydown', function(event) {
        // Check for a backspace
        if (event.which == 8) {
            s = window.getSelection();
            r = s.getRangeAt(0)
            el = r.startContainer.parentElement
            // Check if the current element is the .label
            if (el.classList.contains('label')) {
                // Check if we are exactly at the end of the .label element
                if (r.startOffset == r.endOffset && r.endOffset == el.textContent.length) {
                    // prevent the default delete behavior
                    event.preventDefault();
                    if (el.classList.contains('highlight')) {
                        // remove the element
                        el.remove();
                    } else {
                        el.classList.add('highlight');
                    }
                    return;
                }
            }
        }
        event.target.querySelectorAll('span.label.highlight').forEach(function(el) { el.classList.remove('highlight');})
    });
    span.label.highlight {
        background: #E1ECF4;
        border: 1px dotted #39739d;
    }
    <div contenteditable="true">
     Hallo, <span class="label">Name</span>|,
     this is a demonstration of placeholders!
    </div>

    我没有执行 del 关键功能,但总体思路是存在的,我认为您可以根据上述示例完成它

        2
  •  0
  •   asmmahmud    7 年前

    <div contenteditable="true" id="editable">
     Hallo, <span class="label">Name</span>|,
     this is a demonstration of placeholders!
    </div>
    

            document.addEventListener('keydown', function (e) {
                var keycode = event.keyCode;
                console.log(keycode);
                if (keycode === 8 || keycode === 46) {
                    var spnLables = document.querySelectorAll('#editable span.label');
                    if (spnLables.length) {
                        Array.prototype.forEach.call(spnLables, function (thisnode) {
                            document.getElementById('editable').removeChild(thisnode);
                        });
    
                    }
    
                }
            });