Tob*_*obi 8 html javascript range selection
我有一个contenteditable div,如下面的HTML所示(插入标记为|).
我想span.label在按下时删除backspace或delete(即跨度作为单个字母,因此对于用户来说,它看起来好像Name在一个单键中被删除)
<div contenteditable="true">
Hallo, <span class="label">Name</span>|,
this is a demonstration of placeholders!
Sincerly, your
<span class="label">Author</span>
</div>
Run Code Online (Sandbox Code Playgroud)
Dek*_*kel 13
您需要检查光标是否位于跨度结束的确切位置,如果是,请将其删除:
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');})
});Run Code Online (Sandbox Code Playgroud)
span.label.highlight {
background: #E1ECF4;
border: 1px dotted #39739d;
}Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true">
Hallo, <span class="label">Name</span>|,
this is a demonstration of placeholders!
</div>Run Code Online (Sandbox Code Playgroud)
我没有实现
del关键功能,但总体思路就在那里,我认为你可以根据上面的例子来完成它
| 归档时间: |
|
| 查看次数: |
2181 次 |
| 最近记录: |