摸鱼的时候写了个简易tab栏,实现删除、添加、切换、编辑基本功能
h5
<main id = "m_body">
<div id="top">
<div id="h_span">
<p id = "0">标签1<span>×</span></p>
<p id = "1">标签2<span>×</span></p>
<p id = "2">标签3<span>×</span></p>
</div>
<p id = "h_add">+</p>
</div>
<main class = "text"></main>
</main>
css
<style>
#m_body{
width: 500px;
height: 300px;
border: 1px solid black;
}
#top{
display: flex;
align-items: center;
justify-content: space-between;
height: 40px;
}
#h_span{
display: flex;
overflow: hidden;
height: 40px;
line-height: 5px;
text-align: center;
}
#h_span p{
width: 60px;
height: 40px;
}
#h_add{
text-align: center;
line-height: 40px;
}
.text{
width: 500px;
height: 260px;
background: orange;
}
input{
width: 60px;
height: 40px;
}
</style>
js
<script>
var that
class Tabs{
// 获取所有的标签
constructor(id){
that = this // this指向外部
this.id = document.getElementById(id)
this.h_add = document.getElementById("h_add")
this.init()
}
// 更新标签和颜色
updateNode(){
this.hspan = document.getElementById("h_span")
this.head = this.hspan.getElementsByTagName("p")
this.main = this.id.getElementsByClassName("text")
}
// 初始化
init(){
this.updateNode()
this.h_add.onclick = this.add
for(let i = 0;i<this.head.length;i++){
this.head[i].index = i
this.head[i].onclick = this.toggle
this.head[i].children[0].onclick = this.remove
this.head[i].ondblclick = this.update
this.main[0].ondblclick = this.update
}
}
//切换
toggle(){
if(this.index == 0){
that.main[0].innerHTML = "这是紫色"
that.main[0].style.background = "purple"
}else if(this.index == 1){
that.main[0].innerHTML = "这是黄色"
that.main[0].style.background = "yellow"
}else if(this.index == 2){
that.main[0].innerHTML = "这是橘色"
that.main[0].style.background = "orange"
}else{
that.main[0].innerHTML = "这是白色"
that.main[0].style.background = "white"
}
}
//添加
add(){
var id = document.createElement("p")
var span = document.createElement("span")
var len = that.head.length+1
id.setAttribute("id",len-1)
id.innerHTML = "标签"+len
span.innerHTML = "×"
that.hspan.appendChild(id)
id.appendChild(span)
that.init()
}
//删除
remove(){
var del = this.parentNode
del.remove()
}
//修改
update(){
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()
}
}
}
}
var tab = new Tabs("m_body")
</script>