案例-使用面向对象写 Tab 栏
·
Yin灏
使用面向对象写 Tab 栏
抽象对象:Tab 对象
- 该对象具有切换功能
- 该对象具有添加功能
- 该对象具有删除功能
- 该对象具有修改功能
var that;
class Tab {
constructor(id) {
that = this;
this.main = document.querySelector(id);
this.add = this.main.querySelector('.tabadd');
this.ul = this.main.querySelector('.firstnav ul:first-child');
this.fsection = this.main.querySelector('.tabscon');
this.init(); // 加载即调用
}
// init 初始化操作,让相关的元素绑定事件
init() {
this.updateNode();
this.add.onclick = this.addTab;
for (var i = 0; i < this.lis.length; i++) {
this.lis[i].index = i;
this.lis[i].onclick = this.toggleTab;
this.remove[i].onclick = this.removeTab;
this.spans[i].ondbclick = this.editTab;
this.sections[i].ondbclick = this.editTab;
}
}
updateNode() {
this.lis = this.main.querySelectorAll('li');
this.sections = this.main.querySelectorAll('section');
this.remove = this.main.querySelectorAll('.icon-guanbi');
this.spans = this.main.querySelectorAll('.firstnav li span:nth-child(1)');
}
// 切换功能
toggleTab() {
console.log(this.index);
that.clearClass();
this.className = 'liactive';
that.sections[this.index].className = 'conactive';
}
clearClass() {
for (var i = 0; i < this.lis.length; i++) {
this.lis[i].className = '';
this.sections[i].className = '';
}
}
// 添加功能
addTab() {
that.clearClass();
var li = '<li class="liactive"><span>新选项卡</span><span class="iconfont icon-guanbi"></span></li>';
var section = '<section class="conactive">测试</section>';
that.ul.insertAdjacentHTML('beforeend', li);
that.fsection.insertAdjacentHTML('beforeend', section);
that.init();
}
// 删除功能
removeTab(e) {
e.stopPropagation();
var index = this.parentNode.index;
that.lis[index].remove();
that.sections[index].remove();
that.init();
if (document.querySelector('liactive')) return;
index--;
that.lis[index] && that.lis[index].click(); // 模拟手动调用点击事件
}
// 修改功能
editTab() {
var str = this.innerHTML;
// 双击禁止选中文字
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
this.innerHTML = '<input type="text" />';
var input = this.children[0];
input.value = str;
input.select(); // 选中文本框中文字
input.onblur = function() {
this.parentNode.innerHTML = this.value;
}
input.onkeyup = function(e) {
if (e.keyCode == 13) {
this.blur();
}
}
}
}
new Tab('#tab');