面向对象案例
1.选项卡切换案例
1.1.css样式
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 400px;
height: 300px;
margin: 200px 0 0 800px;
border: 1px solid #000;
}
.tits{
width: 400px;
height: 40px;
}
.tits li{
width: 98px;
height: 38px;
float: left;
border: 1px solid #000000;
font-size: 20px;
line-height: 38px;
text-align: center;
list-style: none;
}
.content{
width: 400px;
height: 260px;
position: relative;
}
.content li{
width: 400px;
height: 260px;
display: none;
position: absolute;
top: 0;
left: 0;
font-size: 40px;
line-height: 260px;
text-align: center;
list-style: none;
}
.box .tits .titsShow{
background: pink;
}
.box .content .contentShow{
display: block;
}
</style>
1.1.html结构
<div class="box">
<ul class="tits ">
<li class="titsShow">音乐</li>
<li>新闻</li>
<li>娱乐</li>
<li>电影</li>
</ul>
<ul class="content">
<li class="contentShow">音乐</li>
<li>新闻</li>
<li>娱乐</li>
<li>电影</li>
</ul>
</div>
1.3.javaScript代码
<script>
var tits = document.querySelectorAll('.tits li');
var cons = document.querySelectorAll('.content li');
var prevIndex = 0;
for(var i = 0;i < tits.length;i++){
tits[i].index=i;
tits[i].onclick=function(){
console.log('我被点击了')
tits[prevIndex].className="";
cons[prevIndex].className="";
tits[this.index].className="titsShow";
cons[this.index].className="contentShow";
prevIndex = this.index;
}
}
</script>
把变量变成对象的属性,此时tish指向对象,对象上的原型上方法只有对象的实例才能调用,也就是说,原型方法上的this指向调用者。
(function(){
function Tab (tits,cons){
this.tits = tits;
this.cons = cons;
this.prevIndex = 0;
}
Tab.prototype.setClass=function(dom,oClass){
dom.className=oClass;
}
Tab.prototype.bindEvent=function(){
var _this=this;
for(var i = 0;i<this.tits.length; i++){
this.tits[i].index=i;
this.tits[i].onclick =function(){
_this.clickHandler(this.index)
}
}
}
Tab.prototype.clickHandler=function(index){
this.setClass(this.tits[this.prevIndex],'')
this.setClass(this.cons[this.prevIndex],'')
this.setClass(this.tits[index],"titsShow");
this.setClass(this.cons[index],"contentShow");
this.prevIndex=index;
}
Tab.prototype.init=function(){
this.bindEvent()
return this
}
function factory (d,c){
return new Tab(d,c).init()
}
window.$=factory;
})()
var tits = document.querySelectorAll('.tits li');
var cons = document.querySelectorAll('.content li');
$(tits,cons)
!!! 以上是DaXiong本人对前端知识的理解总结,如内容知识有错误可以留言修改。
!!!如果以上内容帮助到了你,点击一下赞或者收藏吧!