简体   繁体   中英

Acquire IMG-element width before it is rendered

I wrote this script so that the wallpaper (picture of an object) on my site is positioned right and centred correctly when the window is resized. Now it works just the way I want, but only when the window resizes, under normal conditions when the window hasn't been resized it apparently can't get the width of the img element cause it doesn't subtract the half of it for the left css property. How do I get it?

HTML:

<div class="wallpaper" id="wallpaper">
    <img src=@bgImage.img id="wallpaperImg" style="height:100%; width: auto; position: fixed;">
</div>

JS:

<script type="text/javascript">
    var screenWidth;
    var screenHight;
    var totalHeight;
    var aspectRatio;

    var blah = false; //Ugly hack

    var navbarSize = 41;
    var wallpaper = $("#wallpaperImg");

    function getAspectRatio(h,w){
        return (h-1)/w; //Ugly hack
    }

    function resizeWallpaper(w,h){
        if(typeof(aspectRatio)==='undefined') aspectRatio = @bgImage.aspectRatio; //delivered by server framework

        totalHeight = (h-navbarSize).toString() + 'px';
        wallpaper.css("height",totalHeight);
        wallpaper.css("width","auto");
        wallpaper.css("left",(w/2)-(wallpaper.width()/2)+'px');
        wallpaper.css("top",'41px');


        if(getAspectRatio(wallpaper.height(),wallpaper.width()) > aspectRatio && blah){
            wallpaper.css("width",(w).toString() + 'px')
            wallpaper.css("height","auto")
            wallpaper.css("top",((h/2)-(wallpaper.height()/2))+20.5+'px');
            wallpaper.css("left",'0px');
        }
    }

    resizeWallpaper($(window).width(),$(window).height());
    blah = true;


    $(window).resize(function() {
        resizeWallpaper($(window).width(),$(window).height());
    });
</script> 

Quick upload of what I'm talking about: Site

You have to wait for the image to download before you can resize it. Surround the initial call in a load handler:

wallpaper.on('load', function() {
    resizeWallpaper($(window).width(),$(window).height());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM