js瀑布流布局

  当我们要在很多地方用到的时候,这时候我们不妨把js封装成对象的方式,好处会有很多。定义对象的方式有5种,最简单的单例模式,工厂模式,构造函数模式,原型模式和混合模式。

这里我们最常用的就是混合模式了,他继承了以上所有的优点,实用灵活。看一个小例子,希望可以对你的理解有点帮助;

这里模拟了一个加载更多插入原瀑布流的方法,子集的宽高是参数可以在window.onresize里面实现随着窗口变化而改变

/*  需传参数
father : "waterFall" //父级ID
chilsNum :20, //子集个数
child : "box", //子集类名
childWidth : 200, //子集宽度
fatherWidth : 1100, //父级宽度
heightPdding : 10, //子集上下间距
 */
    function waterFall(opations){
            this.father = document.getElementById(opations.father);
            this.liNum = 0;
            this.childs = this.father.children;
            this.liWidth =  opations.childWidth || this.childs[0].offsetWidth;
            this.fatherWidth = opations.fatherWidth || this.father.offsetWidth;
            this.childNum = 0;
            this.padding =0;
            this.heightPdding = Number(opations.heightPdding);
this.arrHeight = [];
            this.minHeight = 0;
            this.maxHeight = 0;
            this.minIdx = 0;
            this.init();
        }
        waterFall.prototype = {
            init:function(){
                this.mune();
                for(var y = 0; y < this.liNum;y++){
                    this.childs[y].style.position = "absolute";
                    this.childs[y].style.width = this.liWidth +"px";
                    if(y < this.childNum){
                        this.childs[y].style.left = (this.liWidth*y+this.padding*(y+1))+"px";
                        this.childs[y].style.top = this.heightPdding+"px";
                        this.arrHeight.push(parseInt(this.childs[y].offsetHeight)+this.heightPdding*2)
                    }else{
                        var b = Math.floor(y/this.childNum);
                        this.minHeight = Math.min.apply(null,this.arrHeight);
                        this.minIdx = this.fountMin();
                        this.childs[y].style.left = (this.liWidth*this.minIdx+this.padding*(this.minIdx+1))+"px";
                        this.childs[y].style.top = this.minHeight +"px";
                        this.arrHeight[this.minIdx] += parseInt(this.childs[y].offsetHeight)+this.heightPdding;
                    }
                }
                this.maxHeight = Math.max.apply(null,this.arrHeight);
                this.father.style.height = this.maxHeight+ "px";
                this.father.style.position = "relative";
                this.father.style.width = this.fatherWidth+ "px";
            },
            mune:function(){
                this.childNum = Math.floor(this.fatherWidth/this.liWidth);
                this.padding = parseInt(this.fatherWidth - this.liWidth*this.childNum)/(this.childNum+1);
                this.liNum = this.childs.length;
            },
            fountMin:function(){
                for(x in this.arrHeight){
                    if(this.minHeight == this.arrHeight[x]){
                        return parseInt(x);
                    }
                }
            },
        }

 

posted @ 2016-11-21 19:33  chengJun—  阅读(302)  评论(0编辑  收藏  举报