window.addEventListener('load', function() {
var that = null;
// 创建一个tab对象
class Tab {
constructor(tab) {
that = this;
this.tab = document.querySelector(tab);
this.addtab = this.tab.querySelector('.addTab');
this.tab_ul = this.tab.querySelector('ul');
this.tab_cont = this.tab.querySelector('.tab_cont');
this.init();
}
// 程序运行时就创建
init() {
this.getNodes();
this.addtab.addEventListener('click', this.addTab);
for (var i = 0; i < this.lis.length; i++) {
this.lis[i].index = i;
this.lis[i].addEventListener('click', this.toggleTab);
this.closeTab[i].addEventListener('click', this.removeTab);
this.spans[i].addEventListener('dblclick', this.updateTab);
this.section[i].addEventListener('dblclick', this.updateTab);
}
}
// 添加
addTab() {
that.clearClass();
var li = document.createElement('li');
li.classList.add('hide_li');
var section = document.createElement('section');
var span = document.createElement('span');
var spn = span.cloneNode(span);
spn.innerHTML = '测试4';
span.innerHTML = '×';
span.className = 'closeTab';
section.innerHTML = '这是测试' + Math.random();
section.classList.add('first_sec');
that.tab_ul.appendChild(li);
li.appendChild(spn);
li.appendChild(span);
that.tab_cont.appendChild(section);
that.init();
}
// 切换
toggleTab() {
that.clearClass();
this.classList.add('hide_li');
that.section[this.index].classList.add('first_sec');
}
// 删除
removeTab(e) {
e.stopPropagation();
var index = this.parentNode.index;
that.lis[index].remove();
that.section[index].remove();
that.init();
if (document.querySelector('.hide_li')) return;
index--;
that.lis[index] && that.lis[index].click();
// that.clearClass();
// that.lis[index - 1].classList.add('hide_li');
// that.section[index - 1].classList.add('first_sec');
// var parent = this.parentNode.parentNode;
// parent.removeChild(this.parentNode);
// var parentSec = that.section[index].parentNode;
// parentSec.removeChild(that.section[this.parentNode.index]);
}
// 修改
updateTab() {
// 将this的innerhtml的值赋予input
var str = this.innerHTML;
// 双击禁止选定文字
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
var input = this.children;
// 双击后生成一个文本框
this.innerHTML = '<input type="text">';
var input = this.children[0];
input.value = str;
input.select();
// 失去焦点时将input中的值赋予给span
input.addEventListener('blur', function() {
this.parentNode.innerHTML = this.value;
});
// 当敲下回车键时也将input中的值 赋予给span
input.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
this.blur();
}
});
}
// 清除样式
clearClass() {
for (var i = 0; i < this.lis.length; i++) {
this.lis[i].className = '';
this.section[i].classList.remove('first_sec');
}
}
// 获取li跟section的功能
getNodes() {
this.lis = this.tab.querySelectorAll('li');
this.section = this.tab.querySelectorAll('section');
// 关闭功能
this.closeTab = this.tab.querySelectorAll('.closeTab');
// 获取第一个span
this.spans = this.tab.querySelectorAll('.tab .tab_nav li span:first-child');
}
}
new Tab('#tab');
});
![]()