为什么javascript中window.onload中的函数等页面加载完就不执行了?

  1. 我想做瀑布流,我的思路是自己创建四列空div来加载图片,设置一个数组,用来记录每次加载图片时该图片的高,然后在加载图片前通过判断数组大小来判断下一个图片加在哪一列,后来我发现图片的加载需要时间,我如果直接获取获取不到,所以就想用window.onload等图片加载完载获取,可是这样图片加载完之后,window.onload中的函数并没有执行。

/**
 * 负责渲染图片的css样式,并且将图片循环渲染到页面
 * @param {Number}   imgWidth       要设置的图片宽度
 * @param {Dom}      childColumns    被添加图片的包裹层,子列 
 * @param {Number}   i               为了循环做准备,初始数字为0.
 * @return {[type]}          [description]
 */
Gallery.prototype.renderStyle = function(imgWidth, childColumns) {

    var j = this.domImgs.length;
    if (this.countI < j) {
        this.domImgs[this.countI].style.width = imgWidth + "px;";
        this.addImage(this.domImgs[this.countI], childColumns,imgWidth, childColumns);

    }
};

/**
 * 负责将每一个图片加到页面中对应的列里
 * @param {Node} image         被加到页面的img元素
 * @param {Node} childColumns  父包裹层的子列
 */
Gallery.prototype.addImage = function(image, childColumns,imgWidth, childColumns) {
        var smalleast = this.getSmalleast();
        if (this.count < 20) {
            childColumns[smalleast].appendChild(image);
            this.childColumnsLength[smalleast]++;
            this.count++;
            this.countI++;
            this.renderStyle(imgWidth, childColumns,this.countI);
        } else {

            window.    onload=function() {
                childColumns[smalleast].appendChild(image);

                console.log(image.clientHeight);
                console.log(image.height);
                console.log(image.offectHeight);
                var height = image.clientHeight;
                this.childColumnsLength[smalleast] += height;
                this.countI++;
                this.renderStyle(imgWidth, childColumns,this.countI);
            };
        }




    }
阅读 5.1k
1 个回答

我不是很确定,但貌似:body.onload 不会考虑你用代码加载的图片,而只会考虑 HTML 中加载的图片。如果你用 JS 加载图片,应该考虑使用 img 的 onload 事件

推荐问题