我需要在同一个输入框中添加标签和文本.普通文本可以一次删除一个字符.将从一个预定义的特定单词集中选择的标签将一次全部删除.普通文本和标签将位于同一个框中.
document.querySelector('.selectable-icons').addEventListener('click',function(e) {
document.querySelector('[contenteditable]').appendChild(e.target.cloneNode(true));
});
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');})
});
[contenteditable] {
border: 1px solid #000;
margin: 0.4em 0;
line-height: 1.4em;
-webkit-appearance: textfield;
appearance: textfield;
}
img {
vertical-align: top;
max-height: 1.4em;
max-width: 1.4em;
}
.selectable-icons img {
cursor: pointer;
}
span.label.highlight {
background: #E1ECF4;
border: 1px dotted #39739d;
}
span.label {
background: #E1ECF4;
border: 1px dotted #39739d;
}
添加标签,但问题是当点击标签时它将它添加到文本框中,当我在该标签后面写文本时,这一切都被添加到相同的标签范围内,并且标签文本全部被删除,而我需要删除一个文本角色一次和标签一次.请建议一个更好的方法来实现这一点与textarea而不是div.
最佳答案
将标记添加到div时,将其contenteditable属性设置为false:
原文链接:https://www.f2er.com/html/425602.htmlel.setAttribute('contenteditable',false);
我希望能解决您的问题 – 请参阅下面的演示:
document.querySelector('.selectable-icons').addEventListener('click',function(e) {
var el = e.target.cloneNode(true);
el.setAttribute('contenteditable',false);
document.querySelector('[contenteditable]').appendChild(el);
});
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');
})
});
[contenteditable] {
border: 1px solid #000;
margin: 0.4em 0;
line-height: 1.4em;
-webkit-appearance: textfield;
appearance: textfield;
}
img {
vertical-align: top;
max-height: 1.4em;
max-width: 1.4em;
}
.selectable-icons img {
cursor: pointer;
}
span.label.highlight {
background: #E1ECF4;
border: 1px dotted #39739d;
}
span.label {
background: #E1ECF4;
border: 1px dotted #39739d;
}