原生JS模拟Bootstrap中的折叠(Collapse)插件

以前实习的时候因为赶时间直接用bootstrap的插件collapse.js做了个折叠菜单, 对于一个原生控来说还是更倾向于自己写一个, 毕竟为了个折叠菜单引入jq和bootstrap有点太臃肿了。 于是又到了考验山寨能力的时候了-_-# 。
原版collapse.js的效果其实也不难,主要是在开合的过程中添加了css3的过渡效果。以下是原版与山寨版demo,同时点击预览,可明显感受到加载速度的区别。
DEMO:
Bootstrap原版Collapse

接下来是本人山寨版(山寨版结构简单,代码轻巧,无依赖^_^):
Collapse by native JS

打包下载出门左转Github ? Collapse By Native JS
以下是代码逻辑:
HTML的结构

Title1

content1
content1
content1
content1
content1
content1
content1
content1
content1

Title2

content2
content2
content2
content2
content2
content2
content2
content2
content2

Title3

content3
content3
content3
content3
content3
content3
content3
content3
content3

Title4

content4
content4
content4
content4
content4
content4
content4
content4
content4

CSS(要山寨就尽量山寨得彻底,外观样式全部从bootstrap的样式搬运过来):

* {
    box-sizing:border-box;
    -webkit-box-sizing:border-box;
}
body {

    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
    margin: 2px;
}

a{
    text-decoration: underline;
    color: #666666;
}
a:hover{
    text-decoration: none;
}
.collapseDiv{
    color: #333;
    border-radius: 4px;
    background-color: #f5f5f5;
    border:1px solid transparent;
    border-color: #ddd;
    box-shadow: 0 1px 1px rgba(0,0,0,.05);
    margin-top: 5px;
    margin-bottom: 0;
}
.collapseDiv h3{
    font-size: 14px;
    font-weight: bold;
    color: #333;
    border-color: #ddd;
    padding-top: 5px;
    padding-right: 15px;
    padding-bottom: 5px;
    padding-left: 15px;
    background-color: #f5f5f5;
    margin: 0;
}


.collapse_body {
    background-color:#fff ;
    position: relative;
    height: 0;
    overflow: hidden;
    -webkit-transition-timing-function: ease;
    -o-transition-timing-function: ease;
    transition-timing-function: ease;
    -webkit-transition-duration: .35s;
    -o-transition-duration: .35s;
    transition-duration: .35s;
    -webkit-transition-property: height, visibility;
    -o-transition-property: height, visibility;
    transition-property: height, visibility
    
}
.collapse_content{
    border-top: 1px solid #ddd;
    background-color:#fff ;
    padding:15px;
}

JS


//接受三个参数,分别是折叠菜单的外包div名称,是否关闭之前的折叠,默认开启的折叠内容
        function Collapse(className,close_prev,default_open){        
        this._elements = [];
        this._className = String(className);
        this._previous = Boolean(close_prev)
        this._default = typeof(default_open)==="number" ? default_open: -1
        this.getCurrent  
        this.init();
    }

    //收集所有折叠菜单的div
    Collapse.prototype.collectElementbyClass = function(){
        this._elements = [];
        var allelements = document.getElementsByTagName("div");

        for(var i=0;i

你可能感兴趣的:(javascript,collapse,bootstrap,原生js)