Packery和imagesLoaded插件无法正常工作?

问题描述:

我在网站上使用Packery并下载了imagesLoaded,但是页面加载时我的图像仍然重叠.可以在此处和我的代码中看到该网站如下:

I'm using Packery on a website and have downloaded imagesLoaded, but still my images overlap on page load. The website can be seen here and my code is as below:

$(document).ready(function() {
var $container = $container.packery({
   itemSelector: "packery-item"
});
$container.imagesLoaded( function() {
   container.packery();
});
});

任何帮助将不胜感激.

Any help would be greatly appreciated.

html代码如下:

The html code looks like this:

<div class="packery js-packery">

<div class="packery-item item"><img src="imgs/cdg5.jpg"></img></div>
<div class="packery-item text"><img src="imgs/text1.png"></img></div>
<div class="packery-item item w2"><img src="imgs/cdg3.jpg"></img></div>
<div class="packery-item gif"><img src="imgs/gif1.gif"></img></div>

</div>

问题是在加载项目中的图像之前先执行包装.因此,Packery无法知道元素的高度.

The problem is that packery is executed before the images in your items are loaded. Because of that Packery can not know how high the element will have to be.

一个解决方案是使用jquery检查是否所有图像都已加载,然后执行Packery.我已经找到了几种方法来解决,在这里似乎是个好人.

A solution for this is to check with jquery if all images are loaded and then execute Packery. I have found several ways to do this, the solution here seems like a good one.

解决此问题的另一种方法是使图像具有固定的CSS高度或具有height属性.但是,只有在图像具有相同的高度或事先知道高度时,您才能执行此操作.

Another way to fix this is to give the images a fixed height in css or with an height attribute. However, you can only do this when the images have the same height or when you know the height in advance.

更新: 这是第一个解决方案的示例代码:

Update: This is an example code for the first solution:

$(document).ready(function(){

    var cnt = $("img").length;
    $("img").one("load", function() {
        cnt--;

        // If all images are loaded, init Packery
        if (cnt === 0)
        {
            $(".js-packery").packery({
               itemSelector: "packery-item"
            });
        }

    }).each(function() {
      if(this.complete) $(this).load();
    });

});