Image with declared width and height renders square before load

后端 未结 6 2533
不思量自难忘°
不思量自难忘° 2021-02-13 11:15

I have images with declared widths and heights, e.g.:

\"bar\"

They are within

6条回答
  •  天命终不由人
    2021-02-13 11:52

    Here i made a FIDDLE for you

    The Main thing is to generate a div around it and setting the height and the width according to what it should be after it loads. then you can load it inside that container and even with a smooth effect ;)

    HTML

    CSS

    .site-wrapper {
        width:960px;
    }
    .lazyload {
        max-width: 100%;
        border: 1px solid #000;
    }
    .lazyload img {
        max-width: 100%;
    }
    

    JAVASCRIPT

    $(document).ready(function() {
        $('.lazyload').each(function() {
            var parentwidth = $(this).parent().width();
            var width  = $(this).attr('data-width');    
            var height = $(this).attr('data-height');
    
            if(parentwidth < width) {
                height = (parentwidth/width*height);
                width = parentwidth;
            }
    
            $(this).css({ width: width+'px', height: height+'px'});
    
        });
    
        // simulating lazyload
        setTimeout(function() {
            $('.lazyload').each(function() {
                img = $('', { 'class': 'lazyloaded' }).css({display: 'none'});
                original = $(this);
                $(img).load( function(){
                    original.append(img);
                    $(this).fadeIn(200);
                }).attr('src', $(this).attr('data-src'));
            });
        }, 5000);
    });
    

    Let me know if this is what you need or not so i can change according to what you need.

提交回复
热议问题