选项卡、自动切换选项卡

1、面向对象方法:

window.onload = function () {
    var t1 = new Tab('div1');  
    t1.init();
    var t2 = new Tab('div2');
    t2.init();
    t2.autoPlay();
};
function Tab(id) {
    this.oParent = document.getElementById(id);
    this.aInput = this.oParent.getElementsByTagName('input');
    this.aDiv = this.oParent.getElementsByTagName('div');
    this.iNow = 0;
}
Tab.prototype.init = function () {
    var This = this;
    for (var i = 0; i < this.aInput.length; i++) {
        this.aInput[i].index = i;
        this.aInput[i].onclick = function () {
            This.change(this);
        };
    }
};
Tab.prototype.change = function (obj) {
    for (var i = 0; i < this.aInput.length; i++) {
        this.aInput[i].className = '';
        this.aDiv[i].style.display = 'none';
    }
    obj.className = 'active';
    this.aDiv[obj.index].style.display = 'block';
};
Tab.prototype.autoPlay = function () {
    var This = this;
    setInterval(function () {
        if (This.iNow == This.aInput.length - 1) {
            This.iNow = 0;
        }
        else {
            This.iNow++;
        }
        for (var i = 0; i < This.aInput.length; i++) {
            This.aInput[i].className = '';
            This.aDiv[i].style.display = 'none';
        }
        This.aInput[This.iNow].className = 'active';
        This.aDiv[This.iNow].style.display = 'block';
    }, 2000);
};
<div id="div1">
    <input class="active" type="button" value="1">
    <input type="button" value="2">
    <input type="button" value="3">
    <div style="display:block">11111</div>
    <div>22222</div>
    <div>33333</div>
</div>

使用方法:

1、创建对象

var 对象名称 = new Tab('包含tab选项卡的div的id');  

2、调用方法

只有选项卡:         对象名称.init();

需要自动播放:      对象名称.autoPlay();

 

posted @ 2017-12-01 17:06  念念念不忘  阅读(204)  评论(0)    收藏  举报