使用jQuery.extend创建一个简单的选项卡插件

选项卡样式如图,请忽略丑陋的样式,样式可以随意更改

使用jQuery.extend创建一个简单的选项卡插件

主要是基于jquery的extend扩展出的一个简单的选项卡插件,注意:这里封装的类使用的是es6中的class,所以不兼容ie8等低版本浏览器呦!想要兼容低版本可以参考思路,然后换成原生的构造函数原型继承方式

以下是 tabs.js 文件:

class Tabs{
constructor(that){
this.that=that;
this.opt={//默认参数,不传走默认
eventN:'click',
btns:['新闻','娱乐','游戏'],
contents:['新闻1','娱乐1','游戏1']
}
}
init(opt){
//是否用默认参数
$.extend(this.opt,opt);//匹配传递进来的配置参数,有就覆盖,没有就用默认的 //创建按钮
this.creatButton();
//创建切换内容
this.creatContents();
//添加功能
this.events(this.opt.eventN);
}
creatButton(){
let html=``;
this.opt.btns.forEach((e,i)=>{
html+=`<button class="${i===0?'action':''}">${e}</button>`;
});
this.that.append(html);
}
creatContents(){
let html=``;
this.opt.contents.forEach((e,i)=>{ html+=`<div class="${i===0?'show':''}">${e}</div>`;
});
this.that.append(html);
} events(evName){ let buts=this.that.find('button'),
contents=this.that.find('div');
buts.on(evName,function () {
buts.removeClass('action');
contents.removeClass('show'); $(this).addClass('action');
let inx=$(this).index('button');
contents.eq(inx).addClass('show');
}); }
}
$.fn.extend({
tabs:function (opt) {
let t=new Tabs(this);//this是jq对象
t.init(opt);
}
})

调用方式:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<style>
#app{
width: 210px;
height: 100px; }
#app button{
width: 70px;
height: 44px;
line-height: 44px;
background: yellow;
border:0;
cursor: pointer;
}
#app button.action{ background: darkorange;
}
#app div{
display: none;
width: 210px;
background: slateblue;
}
#app div.show{
display: block;
} </style> </head>
<body> <section id="app">
</section>
<script src="./jquery.js"></script>
<script src="./tabs.js"></script>
<script> $('#app').tabs({
eventN:'mouseover',//默认click
btns:['新闻1','娱乐2','游戏1'],
contents:['新闻内容','娱乐内容','游戏内容']
}); </script>
</body>
</html>

赋值代码,效果就可以呈现!

上一篇:微信公众号开发 [05] 微信支付功能开发(网页JSAPI调用)


下一篇:yarn资源调度(网络搜集)