加载JavaScript的图像 - 使用jQuery Masonry [英] Images loaded JavaScript - Using jQuery Masonry

查看:137
本文介绍了加载JavaScript的图像 - 使用jQuery Masonry的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从头开始构建tumblr主题,并使用 masonry 。尽管有时它与图片重叠,但不会添加任何装订线,计算出最高的错误,并且我不确定发生了什么。
我尝试添加 imagesloaded 图书馆,但我不认为它在开玩笑,因为它有时还会重叠图片等。



图片的宽度和高度都是在CSS上定义的,因为它们的宽度都是相同的,但高度不同。 HTML / p>

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

{block:Posts}
< div class =containerid ={postID}>

{block:Photo}
< div class =photo inner>
< a href ={permalink}>
< / a>< / div>
{/ block:Photo}
< / div>

{/ block:Posts}
< / div>

JS

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


解决方案

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

$ p $ $(document).ready(function(){
//计算石匠中的图片div
num_images = $(#content img)。length

//设置一个计数器来跟踪已加载的数量
img_counter = 0;

//当每个图像加载时,递增计数器,如果它们都加载完毕,
//调用砌体。
$(#content img)。 on('load',function(){
img_counter ++;
if(img_counter == num_images){
//我似乎已经决定两次调用masonry来帮助修复故障!
//这是我在代码中找到的。
$(#content)。masonry('reloadItems')。masonry();
}
}) ;
});

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






更新:



我刚刚发现砌体文档中的这一部分,我不记得从我与砌体工作的时间:

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



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

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

然后布局工作并且重叠消失。所以如果我们等待足够长的时间,那么调用布局方法可以解决您的问题。我们面临的挑战是弄清楚我们需要等待的东西!一些选项:


  1. 尝试使用imagesLoaded或我的图像计数器方法,但使用$ tumblelog.masonry('layout')

  2. 上面的URL表示网络字体也会干扰砌体布局,因此只有在图像字体已经加载(承诺可以提供帮助)时安装webfontloader并调用('layout')这个)
  3. 只需使用一个超时 - 有点哈克!

    window.setTimeout(function(){
    $ tumblelog.masonry('layout')
    },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字体。



    使用这个JS:

      docReady(function (){

    //异步加载Google web字体脚本,就好像它包含在
    //< head>元素中一样
    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);

    //当我们有脚本时,加载字体
    wf.onload = function() {
    WebFont.load({

    //将字体系列放在这里。您可以从通常的Google字体页面获取这些信息;
    //复制粘贴CSS网址,选择'JavaScript'选项卡和
    //您将看到您选择的字体的族定义。
    google:{families:['Arvo :: latin']},

    //加载字体时,解析其Deferred对象。
    active:function(){
    console.log(Fonts active)
    fonts_loaded.resolve()
    }
    });
    }

    //设置两个Deferred对象,以跟踪图像和字体。
    var images_loaded = $ .Deferred()
    var fonts_loaded = $ .Deferred()

    //当两个承诺都完成时,重做砌体布局。
    $ .when(images_loaded,fonts_loaded).done(function(){
    console.log(Redoing Masonry);
    //尝试注释掉这一行;没有它, '找到任何图片
    //并且布局应该是标准HTML。
    $(#content)。masonry('reloadItems');

    //尝试评论出来这一行;没有它,布局算法应该是
    //弄乱了,并且图像将重叠。
    $(#content)。masonry('layout');
    });

    //使用Masonry的imagesLoaded插件处理图片加载过程。
    $(#content)。imagesLoaded(function(){
    console.log(Images loaded)
    images_loaded.resolve();
    });
    });

    更新这一行的字体定义:

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


    I am building a tumblr theme from scratch and I'm using masonry. Although, sometimes it overlaps pictures, it doesn't add any gutter, calculates top wrong, and I'm not sure of what's happening. I tried adding imagesloaded library but I don't think it's woking since it's still overlapping pictures, etc, sometimes.

    Images width and height are defined on the CSS since they're all the same width but different heights.

    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 );
    });
    

    解决方案

    I had a similar issue with Masonry, with a project that is now unfortunately offline, so I cannot give you a URL. I dug up the code, and my workaround was:

    $(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();
            }
        });
    });
    

    That's jQuery-flavoured; it doesn't look like you're using jQuery, but I hope it helps.


    Update:

    I just found this section of the masonry docs, which I don't remember from my time with Masonry:

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

    If I wait for your tumblr page to finish loading, then open the console, and type in:

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

    then the layout works and the overlap vanishes. So if we wait long enough, then calling the layout method fixes your problem. The challenge is to work out what we need to wait for! Some options:

    1. Try the imagesLoaded or my image counter approach, but use $tumblelog.masonry('layout')
    2. the URL above says web fonts also interfere with Masonry layout, so install the webfontloader and call ('layout') only when the images and the fonts have loaded (promises can help with this)
    3. Just use a timeout - a bit hacky!

      window.setTimeout(function() { $tumblelog.masonry('layout') }, 1000)

    and adjust the value of the timeout until it works.


    Second update

    Here's a fiddle showing how to redo the layout of Masonry after fonts and images have both loaded:

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

    I don't know how tumblr loads content into your template, but I reckon the problem arises due to a mess of complexity associated with inserting content into the DOM, so I have tried to recreate that by adding your images using JS. Within the fiddle, there's a JS line that if you comment it out then re-run the fiddle, seems to recreate the overlap problem.


    Quick Tumblr Hack

    In your template where you are working with docReady, try this:

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

    After two seconds that will call Masonry to redo the layout. If if works, then you know the problem is definitely something to do with waiting for the right combination of things to load.


    Essential code

    To integrate my fiddle,

    Remove your CSS that loads the Google Font.

    Use this 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();
        });
    });
    

    Update the font definitions in this line:

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

    这篇关于加载JavaScript的图像 - 使用jQuery Masonry的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆