<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Tag Input</title>
</head>
<body>
<form class="tag-form" action="#">
<ul class="tag-list">
<li class="tag-input-wrap">
<input class="tag-input" type="text" placeholder="タグを入力">
</li>
</ul>
</form>
</body>
</html>
*, *:before, *:after {
margin: 0;
padding: 0;
border: 0;
box-sizing: border-box;
line-height: 1;
font-family: "Helvetica Neue", "メイリオ", Meiryo, Helvetica, Arial, "游ゴシック", YuGothic, "ヒラギノ角ゴ ProN W3", "Hiragino Kaku Gothic ProN", "MS Pゴシック", "MS PGothic", sans-serif;
}
body {
padding: 1em;
background: rgb(255,255,255);
color: #222;
}
.tag-list {
display: flex;
flex-wrap: wrap;
max-width: 600px;
padding: 0 5px 5px;
background: #fff;
border: 1px solid #555;
list-style: none;
}
.tag-list li {
margin: 5px 5px 0 0;
}
.tag-list .tag-input-wrap {
flex: auto;
min-width: 100px;
}
.tag-list li a {
position: relative;
display: block;
min-width: 30px;
height: 30px;
padding: 0 5px;
background: #555;
color: #fff;
border-radius: 4px;
font-size: 14px;
line-height: 30px;
text-align: center;
text-decoration: none;
}
.tag-list li a:hover:after,
.tag-list li a:focus:after {
content: "×";
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
padding: 0 5px;
background: rgba(0, 0, 0, .5);
border-radius: 4px;
line-height: 30px;
text-align: center;
}
.tag-list li .tag-input {
display: block;
width: 100%;
height: 30px;
padding: 0 5px;
outline: none;
font-size: 14px;
line-height: 30px;
}
var $form,
$input,
$list;
document.addEventListener("DOMContentLoaded", start);
function start() {
$form = document.querySelector(".tag-form");
$list = document.querySelector(".tag-list");
$input = document.querySelector(".tag-input");
$form.onsubmit = onSubmit;
// keypressで動作させる場合↓
// $input.addEventListener("keypress", onKeyInput);
}
function onSubmit() {
addTagFromInput();
return false;
}
function onKeyInput(event) {
console.log(event);
if (event.key != "Enter") return;
addTagFromInput();
}
function addTagFromInput() {
var name = $input.value.replace(/^\s+/, "");
if (name.length < 1) return;
addTag(name);
$input.value = "";
}
function addTag(name) {
var $tag_li = document.createElement("li"),
$tag_a = document.createElement("a");
$tag_a.innerText = name;
$tag_a.href = "#";
$tag_a.addEventListener("click", function (event) {
event.preventDefault();
$tag_li.remove();
return false;
});
$tag_li.appendChild($tag_a);
// リストの最後の要素(.tag-input)の前に挿入
var len = $list.children.length;
$list.insertBefore($tag_li, $list.children[len-1]);
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.