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

本文介绍了一个基于jQuery的简单选项卡插件实现方法,使用ES6语法编写,包括按钮和内容切换功能。该插件不兼容IE8及更低版本浏览器。

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

主要是基于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>

 

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

 

转载于:https://www.cnblogs.com/xinxinxiangrong7/p/9588355.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值