console
var input = document.getElementById('js-input');
var list = document.getElementById('js-list');
var txtList = [];
input.addEventListener('keyup', function(e) {
if (e.keyCode == 13 && input.value !== '') {
txtList.push(input.value);
addLiTag(input.value);
input.value = '';
} else {
list.innerHTML = '';
search(input.value);
}
});
list.addEventListener('click', function(e) {
if (e.target.tagName === 'STRONG') {
var targetLi = e.target.parentNode;
var targetTxt = targetLi.children[0].innerText;
var index = txtList.indexOf(targetTxt);
if (index > -1) {
txtList.splice(index, 1);
}
list.removeChild(targetLi);
}
})
function addLiTag(val) {
var ndLi = document.createElement('li');
ndLi.setAttribute('class', 'clearfix');
ndLi.innerHTML = '<span class="fl js-li">' + val + '</span><strong class="fr js-delete">×</strong>';
list.appendChild(ndLi);
}
function search(str) {
var ndList = document.getElementsByClassName('js-li');
for (var i = 0; i < txtList.length; i ++) {
var txt = txtList[i];
var reg = new RegExp(str, 'g');
if (reg.test(txt)) {
var replaceTxt = '<span class="red">' + str + '</span>';
var result = txt.replace(reg, replaceTxt);
addLiTag(result);
}
}
}
<div class="container">
<h2>todos</h2>
<div class="content">
<div class="pr">
<i class="u-tip">^</i>
<input id="js-input" />
</div>
<ul id="js-list"></ul>
</div>
</div>
* {
margin: 0;
padding: 0;
}
body {
background: #f5f5f5;
color: #666;
}
.clearfix {
zoom: 1;
}
.clearfix::after {
display: block;
overflow: hidden;
content: "";
height: 0;
}
.fl {
float: left;
}
.fr {
float: right;
}
.pr {
position: relative;
}
.container {
width: 80%;
margin: 50px auto;
}
h2 {
color: #ebdddd;
font-size: 40px;
font-weight: normal;
text-align: center;
}
.content {
width: 100%;
margin: 0 auto;
text-align: center;
}
.u-tip {
position: absolute;
top: 50%;
left: 50%;
margin-top: -12px;
margin-left: -135px;
transform: rotate(180deg);
color: #e5e5e5;
font-style: normal;
font-weight: bold;
}
input {
display: inline-block;
width: 250px;
height: 40px;
padding: 5px 10px 5px 25px;
border: 1px solid #f1f1f1;
}
ul {
list-style: none;
}
li {
display: block;
width: 250px;
height: 30px;
line-height: 30px;
margin: 0 auto;
padding: 5px 10px 5px 25px;
border: 1px solid #e0e0e0;
background: #fff;
}
.js-delete:hover {
color: saddlebrown;
cursor: pointer;
}
.red {
color: red;
}