琢磨出的一个写法
<style type="text/css">
* {
padding: 0;
margin: 0;
}
.box>div {
width: 300px;
height: 300px;
border: 1px solid black;
display: none;
}
.box {
position: relative;
}
.box div:nth-child(2) {
position: absolute;
top: 0;
background: green;
}
.box div:nth-child(3) {
position: absolute;
top: 0;
background: salmon;
}
.show {
display: block !important;
background: tomato;
}
#list {
width: 300px;
height: 50px;
border: 1px solid black;
/* margin: 0 auto; */
text-align: center;
}
#list ul {
list-style-type: none;
}
#list ul li {
float: left;
margin: 0px 16px;
cursor: pointer;
height: 50px;
text-align: center;
border-right: 1px solid black;
}
.active {
background: #ccc;
}
</style>
</head>
<body>
<div id="list">
<ul>
<li class=a ctive>房产</li>
<li>家具</li>
<li>二手房</li>
</ul>
</div>
<div class="box">
<div class="show">1111</div>
<div>22</div>
<div>333</div>
</div>
</body>
<script>
function Tabs() {
this. tli = document.querySelectorAll('#list>ul>li')
this. tdiv = document.querySelectorAll('.box>div')
}
Tabs.prototype.fn = function () {
var that = this
for (var i = 0; i < this.tli.length; i++) {
this.tli[i].index = i;
this .tli[i].onclick = function () {
// console.log(this)
that.myclick(this);//
}
}
}
Tabs.prototype.myclick = function (that) {
for (var j = 0; j < this.tdiv.length; j++) {
this.tdiv[j].setAttribute('class', '')
this.tli[j].setAttribute('class', '')
}
that.setAttribute('class', 'active')
this.tdiv[that.index].setAttribute('class', 'show')
}
var tabs = new Tabs()
tabs.fn()
</script>