入力したすべての項目がタグに変換され、それぞれが文字(カンマまたはスペースなど)で区切られたWebサイト機能を実現しようとしています。 。私が欲しいのは、入力した項目のtextContent
を含む.tags
にkeyup
にspan
を追加する必要があります。ユーザーが項目の名前を入力すると、そのtextContent
がライブ更新されます。私が得た結果は1文字ごとにspan
でした。要約すると「1文字、1タグ」であり、コンマがある場合は空白のタグを挿入します。入力フィールドは、文字列の各単一文字のtextContentsを持つタグを返します
var query = document.querySelector.bind(document);
query('#textfield').addEventListener('keyup', insertTag);
function insertTag(e) {
var evt = e.target;
if(evt.value) {
var items = evt.value.split(',');
for(var i = 0; i < items.length; i++) {
var span = document.createElement('span');
span.textContent = items[i];
evt.nextElementSibling.appendChild(span);
}
}
}
section {
width: 100%;
height: 100vh;
background: firebrick;
position: relative;
}
section .container {
max-width: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
section #textfield {
width: 512px;
border: 2px solid #ccc;
background: transparent;
color: #eee;
padding: 0.5rem;
border-radius: .3rem;
}
section #textfield::placeholder {
font: 0.8rem 'Arial', sans-serif;
color: rgba(255,255,255,0.4);
}
section .tags {
display: grid;
grid-template-columns: 33% 33% 33%;
grid-gap: 5px;
margin-top: 1rem;
}
section .tags > span {
background: maroon;
color: #ddd;
text-align: center;
font: 1rem 'Arial', sans-serif;
padding: 0.7rem 1rem;
border-radius: .25rem;
cursor: pointer;
position: relative;
}
section .tags > span:after {
content: 'Remove';
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-align: center;
line-height: 2.5;
border-radius: inherit;
background: rgba(0,0,0,0.6);
display: none;
}
section .tags > span:hover {
font-size: 0;
}
section .tags > span:hover:after {
display: block;
font-size: 1rem;
}
<section>
<div class="container">
<input id="textfield" type="text" name="tag" placeholder="Enter an item and press Enter to add to list">
<div class="tags"></div>
</div>
</section>
私は誰かが私はこの問題を解決するに役立つだろう願っています。
PS。私の正気を許してください。
https://jsfiddle.net/wostex/vppo65tw/?あなたが必要とするものは明確ではありません。 – wostex
@wostexスニペットでは、常に1つのタグしか持たないでしょう。 入力値全体のタグを作成する際に、既存のタグをリセットするのを忘れてしまったようです。さらに、挿入するタグに文字が含まれていて空でないかどうかを確認する必要があります。 – Eytibi