簡體   English   中英

在渲染之前獲取IMG元素的寬度

[英]Acquire IMG-element width before it is rendered

我編寫此腳本是為了使我的站點上的牆紙(對象的圖片)在調整窗口大小時正確定位並正確居中。 現在它按照我想要的方式工作,但是只有當窗口調整大小時,在正常情況下,當窗口沒有調整大小時,它顯然無法獲得img元素的寬度,因為它不會減去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> 

快速上傳我正在談論的內容: 網站

您必須等待圖像下載,然后才能調整其大小。 將初始調用包含在負載處理程序中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM