Contenteditable:如何在按del或退格时完全删除跨度

时间:2017-08-10 23:54:31

标签: javascript html range selection

我有一个contenteditable div,如下面的HTML所示(插入符号为capture { puts 'xyz' } => 'xyz\n' )。

我想在按退格删除时删除|(即跨度充当单个字母,因此对用户而言,它看起来好像span.label已在一个按键中被删除)

Name

2 个答案:

答案 0 :(得分:10)

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



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>
&#13;
&#13;
&#13;

  

我没有实现del密钥功能,但总体思路就在那里,我认为你可以根据上面的例子来完成它

答案 1 :(得分:0)

您可以在div上听取onKeyDown事件:

<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);
                    });

                }

            }
        });
相关问题