我有一个contenteditable div,如下面的HTML所示(尖号标记为|
)。
我想在按Backspace或Delete时删除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>
最佳答案
您需要检查光标是否位于跨度末端的确切位置,如果是,则将其删除:
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>
关于javascript - 可编辑的: How to completely remove span when pressing del or backspace,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45625049/