steps
- Create a custom constructor that puts properties inside the constructor and methods inside the constructor’s prototype object (reduces memory consumption)
- An instantiation object is created using the constructor, and a method in the constructor is called using the instance object
In general, you can solve the problem in a process-oriented way, and then implement it in an object-oriented way.
eg1:
Object oriented TAB bar toggle note that in the prototype this points to: In the outer layer of the prototype object, this points to the instance object. If there is an event (such as a click event) in the prototype object, note that this points to the click event. You need to change the direction of this,fn.bind(parameter 1,). You can also change the this pointer by using the arrow function, which points to the this pointer above
- HTML structure
<div class="tabbox">
<ul>
<li class="mark">1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li class="mark">1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
Copy the code
- CSS styles
* {
margin: 0;
padding: 0;
}
.tabbox {
width: 450px;
height: 300px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)}ul.ol {
list-style: none;
}
ul {
width: 450px;
height: 50px;
}
ul>li {
width: 150px;
height: 50px;
color: white;
font-size: 30px;
background-color: #ccc;
line-height: 50px;
float: left;
text-align: center;
}
ol {
width: 450px;
height: 250px;
}
ol>li {
width: 450px;
height: 250px;
font-size: 80px;
color: white;
background-color: # 666;
text-align: center;
line-height: 250px;
position: absolute;
z-index: 0;
}
ul>li.mark {
background-color: tomato;
}
ol>li.mark {
background-color: aqua;
z-index: 1;
}
Copy the code
- Js behavior
function Tb(selector1, selector2) {
this.uls = document.querySelectorAll(selector1);
this.ols = document.querySelectorAll(selector2)
}
Tb.prototype.move = function () {
for (let i = 0; i < this.uls.length; i++) {
this.uls[i].onclick = () = > {
for (let j = 0; j < this.uls.length; j++) {
this.uls[j].className = ' ';
this.ols[j].className = ' ';
}
this.uls[i].className = 'mark';
this.ols[i].className = 'mark'; }}}let table = new Tb("ul>li"."ol>li");
table.move();
Copy the code