问题描述
我正在尝试模仿 Stack Overflow 上的标签功能,当您单击文本框上的 space 按钮时,它会为 textBox
中的前一个文本添加一个蓝色边框并在其旁边添加一个 X 按钮以根据需要将其删除。
这是我正在尝试做的一个图像示例:
。这是我目前所拥有的。如果有人能帮助我,我将不胜感激。
<input id="tags">
<script>
document.getElementById("tags").addEventListener('keydown',function (event) {
if (event.keyCode === 32) {
// what do I fill in here??
}
});
</script>
解决方法
看看 HTML 的样子:
<div class="js-tag-editor tag-editor multi-line s-input" style="padding: 0px 9.1px; box-sizing: border-box; margin-top: 0px; margin-bottom: 0px; width: 100%;">
<span><span class="s-tag rendered-element">javascript<a class="js-delete-tag s-tag--dismiss" title="Remove tag"><svg class="svg-icon iconClearSm pe-none" width="14" height="14" viewBox="0 0 14 14">
<path d="M12 3.41L10.59 2 7 5.59 3.41 2 2 3.41 5.59 7 2 10.59 3.41 12 7 8.41 10.59 12 12 10.59 8.41 7z">
</path>
</svg></a></span>
<span class="s-tag rendered-element">arrays<a class="js-delete-tag s-tag--dismiss" title="Remove tag"><svg class="svg-icon iconClearSm pe-none" width="14" height="14" viewBox="0 0 14 14">
<path d="M12 3.41L10.59 2 7 5.59 3.41 2 2 3.41 5.59 7 2 10.59 3.41 12 7 8.41 10.59 12 12 10.59 8.41 7z">
</path>
</svg></a></span>
<span class="s-tag rendered-element">javascript-events<a class="js-delete-tag s-tag--dismiss" title="Remove tag"><svg class="svg-icon iconClearSm pe-none" width="14" height="14" viewBox="0 0 14 14">
<path d="M12 3.41L10.59 2 7 5.59 3.41 2 2 3.41 5.59 7 2 10.59 3.41 12 7 8.41 10.59 12 12 10.59 8.41 7z">
</path>
</svg></a></span>
<span class="s-tag rendered-element">javascript-objects<a class="js-delete-tag s-tag--dismiss" title="Remove tag"><svg class="svg-icon iconClearSm pe-none" width="14" height="14" viewBox="0 0 14 14">
<path d="M12 3.41L10.59 2 7 5.59 3.41 2 2 3.41 5.59 7 2 10.59 3.41 12 7 8.41 10.59 12 12 10.59 8.41 7z">
</path>
</svg></a></span>
</span>
<input type="text" autocomplete="off" tabindex="103" placeholder="" id="tageditor-replacing-tagnames--input" class="s-input js-tageditor-replacing" style="width: 19px;"><span></span>
</div>
它是 <span>
后跟一个输入。它在用户看来有点像输入实际上是整行,但事实并非如此 - 输入只是右侧可打字的部分。
要添加边框,请使用 CSS。要删除附加元素,请对其调用 .remove()
。类似的东西:
const input = document.querySelector("input");
input.addEventListener('keydown',(event) => {
if (event.keyCode === 32) {
const span = input.insertAdjacentElement('beforebegin',document.createElement('span'));
span.textContent = input.value;
const x = span.appendChild(document.createElement('button'));
x.textContent = 'x';
x.onclick = () => span.remove();
input.value = '';
}
});
.tag-container {
border: 1px solid black;
}
.tag-container span {
background-color: lightblue;
border: 1px solid blue;
padding-left: 1em;
margin-right: 1em;
}
.tag-container span button {
margin-left: 1em;
}
.tag-container input:focus,.tag-container input {
outline: none;
border: 0;
}
<div class="tag-container">
<input>
</div>