javascript – Contenteditable:如何在按del或退格键时完全删除span

前端之家收集整理的这篇文章主要介绍了javascript – Contenteditable:如何在按del或退格键时完全删除span前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 contenteditable div,如下面的HTML所示(插入符号为|).

我想在按退格键或删除删除span.label(即,span作为单个字母,因此对于用户来说,它看起来好像在一个单键中删除了Name)

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

解决方法

您需要检查光标是否位于跨度结束的确切位置,如果是,请将其删除
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,this is a demonstration of placeholders!
</div>

I didn’t implement the del key functionality,but the general idea is there and I think you can complete it based on the above example

原文链接:https://www.f2er.com/js/150176.html

猜你在找的JavaScript相关文章