在呈现之前获取IMG元素宽度

时间:2012-11-25 15:10:43

标签: javascript jquery html

我编写了这个脚本,以便在调整窗口大小时,我网站上的壁纸(对象的图片)位于正确的位置并正确居中。现在它按照我想要的方式工作,但只有当窗口调整大小时,在正常条件下窗口没有调整大小时,它显然无法获得img元素的宽度,因为它不会减去它的一半左css属性。我怎么得到它?

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> 

快速上传我正在谈论的内容:Site

1 个答案:

答案 0 :(得分:1)

您必须等待图像下载才能调整大小。在加载处理程序中包围初始调用:

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