5
我需要在同一個輸入框中添加標籤和文本。普通文本可以一次刪除一個字符。將從預先定義的一組特定詞中選擇的標籤將一次全部刪除。正常的文本和標籤將在同一個盒子上。需要在同一輸入框中添加標籤和普通文本
鏈接擺弄link 到目前爲止,我已經試過
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;
}
<p>Just click on an icon to add it.</p>
<div class="custom-input">
<div class="selectable-icons">
<span class="label"> Tag </span>
<span class="label"> Tag 2 </span>
<span class="label">Tag 3</span>
</div>
<div contenteditable="true">
You can type here. Add an icon.
</div>
</div>
添加標籤,但問題是,當點擊該標籤是將其添加到文本框,當我在該標籤之後寫入文本,將所有內容添加到相同的標籤範圍,並將標籤+文本全部一起刪除,而我需要將文本同時刪除一個字符並將標籤一次全部刪除。請建議一個更好的方式來實現這與textarea而不是div。
注意:如果我更改了也是可編輯的範圍內的標籤數據。在標籤的可編輯的div和文本
工程很好。請建議一種方式,我可以在用戶可編輯的textarea而不是div @kukkuz –
@sercha with'textarea'?我不太確定如何去... – kukkuz
沒問題。你可以添加一個功能,如果我改變標籤數據反映在可編輯的div –