图像加载JavaScript - 使用jQuery Masonry

时间:2014-08-05 22:22:57

标签: javascript html jquery-masonry

我正在从头开始构建一个tumblr主题,我正在使用masonry。虽然,有时它会重叠图片,但它不会添加任何装订线,计算出错误,我不确定发生了什么。 我尝试添加imagesloaded库,但我不认为这是因为它仍然会重叠图片等,有时也是如此。

图像宽度和高度在CSS上定义,因为它们的宽度相同但高度不同。

HTML

<div class="masonry js-masonry"  data-masonry-options='{ "isFitWidth": true, "gutter": 14}' id="content">

 {block:Posts}
 <div class="container" id="{postID}">

      {block:Photo}
      <div class="photo inner">
        <a href="{permalink}">
          <img src="{block:indexpage}{PhotoURL-500}{/block:indexpage}{block:permalinkpage}{PhotoURL-HighRes}{/block:permalinkpage}" alt="{PhotoAlt}">
        </a></div>
        {/block:Photo}
      </div>

      {/block:Posts}          
    </div>

JS

var container = document.querySelector('#content');
var msnry;
imagesLoaded( container, function() {
  msnry = new Masonry( container );
});

2 个答案:

答案 0 :(得分:0)

我与Masonry有类似的问题,现在一个项目不幸脱机,所以我不能给你一个URL。我挖出了代码,我的解决方法是:

$(document).ready(function() {
    // Count the images in the masonry div
    num_images = $("#content img").length

    // Set a counter to track how many have loaded.
    img_counter = 0;

    // As each image loads, increment the counter. If they are all loaded,
    // call masonry.
    $("#content img").on('load', function() {
        img_counter++;
        if (img_counter == num_images) {
            // And I seem to have settled on calling masonry twice to help fix the glitch!
            // This is as I found it in my code.
            $("#content").masonry('reloadItems').masonry();
        }
    });
});

这是jQuery风格的;它看起来并不像你使用jQuery,但我希望它有所帮助。


<强>更新

我刚刚找到了砌体文档的这一部分,我从与砌体的时间不记得了:

http://masonry.desandro.com/appendix.html#imagesloaded

如果我等待您的tumblr页面完成加载,请打开控制台,然后输入:

var $tumblelog = $('#content');
$tumblelog.masonry('layout')

然后布局工作,重叠消失。因此,如果我们等待足够长的时间,那么调用布局方法可以解决您的问题。挑战在于找出我们需要等待的东西!一些选择:

  1. 尝试使用imagesLoaded或my image counter方法,但请使用$ tumblelog.masonry(&#39; layout&#39;)
  2. 上面的网址说网络字体也会影响Masonry布局,所以只有当字体加载时才安装webfontloader并调用(&#39; layout&#39;)承诺可以帮助这个)
  3. 只需使用超时 - 有点hacky!

    window.setTimeout(function(){     $ tumblelog.masonry(&#39;布局&#39;) },1000)

  4. 并调整超时值直到它起作用。


    第二次更新

    这里是一个小提琴,展示了在字体和图片都加载后如何重做砌体的布局:

    http://jsfiddle.net/sifriday/5xotLj23/3/

    我不知道tumblr如何将内容加载到您的模板中,但我认为由于将内容插入DOM而导致的复杂性导致问题出现,因此我尝试使用添加图像来重新创建JS。在小提琴中,有一条JS系列,如果你把它评论出来然后重新运行小提琴,似乎重新创建了重叠问题。


    Quick Tumblr Hack

    在使用docReady的模板中,试试这个:

    docReady( function() {
        window.setTimeout(function() {
            $("#content").masonry('layout');
        }, 2000);
    });
    

    两秒后,将调用Masonry重做布局。如果有效,那么你知道问题肯定与等待正确的事物组合加载有关。


    基本代码

    整合我的小提琴,

    删除加载Google字体的CSS。

    使用此JS:

    docReady(function() {
    
        // Asynchronously load the Google web fonts script, as if it was included in the 
        // <head> element.
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
          '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
    
        // When we have the script, load the fonts.
        wf.onload = function() {
            WebFont.load({
    
                // Put your font families here. You can get these from the usual Google Fonts page;
                // from the bit where you copy-paste the CSS URL, select the 'JavaScript' tab and
                // you will see the families definition for the fonts you have selected.
                google: { families: [ 'Arvo::latin' ] },
    
                // When the font is loaded, resolve its Deferred object.
                active: function() {
                    console.log("Fonts active")
                    fonts_loaded.resolve()
                }
            });
        }
    
        // Set up two Deferred objects, to track images and fonts.
        var images_loaded = $.Deferred()
        var fonts_loaded = $.Deferred()
    
        // When both promises complete, redo the Masonry layout.
        $.when(images_loaded, fonts_loaded).done(function() {
            console.log("Redoing Masonry");
            // Try commenting out this line; without it, masonry won't find any images
            // and the layout should be standard HTML.
            $("#content").masonry('reloadItems');
    
            // Try commenting out this line; without it, the layout algorithm should be
            // messed up, and the images will overlap.
            $("#content").masonry('layout');
        });
    
        // Deal with the image loading process using Masonry's imagesLoaded plugin.
        $("#content").imagesLoaded(function() {
          console.log("Images loaded")
          images_loaded.resolve();
        });
    });
    

    更新此行中的字体定义:

    google: { families: [ 'Arvo::latin' ] },
    

答案 1 :(得分:0)

请使用以下代码imagesloaded plugin

jQuery(document).ready(function(){
    imagesLoaded( 'body', function() {
        jQuery('.js-masonry').masonry('layout');
    });
});

当您将砌体用作<div class="masonry js-masonry" data-masonry-options='{ "isFitWidth": true, "gutter": 14}' id="content">....</div>

时,这是最简单的解决方案