var tagInput = {
isInited: false,
init: init,
bindEvent: bindEvent,
addTag: addTag,
removeTag: removeTag,
};
tagInput.init();
function init() {
var that = this;
if (that.isInited) return;
that.isInited = true;
// 请修改这一行代码,保存class为js-input的输入框的dom元素引用
that.input = document.querySelector(".js-input");
that.bindEvent();
}
function bindEvent() {
var that = this;
var input = that.input;
if (!input) return;
input.addEventListener("keydown", function (event) {
// 请修改这一行代码,判断用户是否按了回车键
var isEnter = false;
if (event.keyCode === 13) isEnter = true;
// 请修改这一行代码,判断用户是否按了删除键
var isDelete = false;
// 当点击为删除键,并且输入框为空内容时,isDelete才为true阻止默认删除事件
if (event.keyCode === 8 && input.value === "") isDelete = true;
(isEnter || isDelete) && event.preventDefault();
isEnter && that.addTag();
isDelete && that.removeTag();
});
input.parentNode.addEventListener("click", function () {
input.focus();
});
}
function addTag() {
var that = this;
// 输入的标签值,去空白
var tagTemp = that.input.value.trim();
// 判断是否存在已存在的标签
var isHave = Array.from(document.querySelectorAll(".tag")).some(
(item) => item.innerText === tagTemp
);
if (tagTemp && !isHave) {
// 有tag元素,则在最后一个tag元素之后插入元素
if (document.querySelectorAll(".tag").length) {
document
.querySelectorAll(".tag")
[document.querySelectorAll(".tag").length - 1].insertAdjacentHTML(
"afterend",
`<span class="tag">${tagTemp}</span>`
);
} else {
// 没有tag则直接在input框前插入
that.input.insertAdjacentHTML(
"beforebegin",
`<span class="tag">${tagTemp}</span>`
);
}
}
// 清空
that.input.value = "";
}
function removeTag() {
var that = this;
var tagTemp = that.input.value;
// 输入框没有任何值并且里面存在tag元素执行删除
if (!tagTemp && document.querySelectorAll(".tag").length) {
document
.querySelector(".tag-input")
.removeChild(
document.querySelectorAll(".tag")[
document.querySelectorAll(".tag").length - 1
]
);
}
}