6.用class封装选项卡
没什么好说的 自己做的
需要注意的是在点击事件中this会被转化为当前的点击元素 我们需要用bind(this)强制把this转换回来 成为class中的this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>选项卡</title>
<script src="../jquery-3.6.0.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
*{
margin: 0;
padding: 0;
list-style: none;
}
#top_change{
overflow: hidden;
width: 210px;
background-color: #CCCCCC;
}
#top_change li{
width: 50px;
height: 50px;
list-style: none;
line-height: 50px;
text-align: center;
background-color: #9ACD32;
margin: 10px;
float: left;
cursor: pointer;
}
#button_change{
width: 210px;
height: 100px;
background-color: #848484;
line-height: 100px;
}
#button_change li{
height: 100px;
width: 210px;
margin: 0;
padding: 0;
text-indent: 50px;
display: none;
}
</style>
</head>
<body>
<div id="top_change">
<li>1</li>
<li>2</li>
<li>3</li>
</div>
<div id="button_change">
<li>
<p>第一个li</p>
</li>
<li>
<p>第二个li</p>
</li>
<li>
<p>第三个li</p>
</li>
</div>
</body>
<script type="text/javascript">
// 只需要输入上面点击的名字 下面点击的名字 即可完成选项卡内容切换
class OptionCade{
constructor(topCades,buttonCades){
this.topCades = document.querySelector(`#${topCades}`)
this.buttonCades = document.querySelector(`#${buttonCades}`)
this.theFirst()
}
theFirst = function(){
// 点击的时候 自己变红 其他变回原貌
for(let i=0;i<this.topCades.children.length;i++){
this.topCades.children[i].onclick = function(){
for(let i=0;i<this.topCades.children.length;i++){
this.topCades.children[i].style.background = "#9ACD32"
this.buttonCades.children[i].style.display = "none"
}
this.topCades.children[i].style.background = "red"
this.buttonCades.children[i].style.display = "block"
}.bind(this) // 把this强制转换为类的this
}
}
}
tianqi = new OptionCade("top_change","button_change")
</script>
</html>

浙公网安备 33010602011771号