面向对象案例
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代码
//1.面向过程的方法去写
<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(我被点击了)
//给上一个元素清除leiming
tits[prevIndex].className="";
cons[prevIndex].className="";
//给元素添加类名
tits[this.index].className="titsShow";
cons[this.index].className="contentShow";
//更新全局的prevIndex
prevIndex = this.index;
}
}
</script>
//2.面向对象的方法去写
把变量变成对象的属性,此时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
}
//创建一个工厂函数(创建实例化对象,不需要用户再new了)
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本人对前端知识的理解总结,如内容知识有错误可以留言修改。