簡體   English   中英

如何從加載時保存圖像的寬度和高度?

[英]How to save image width and height from onload?

我嘗試將一系列<li>元素制作成輪播,只是我希望如果圖像大小大於640x480,並且將其居中放置,則要調整圖像的大小。

我有以下代碼:HTML:

<ul id="carousel">      
    <li><img src="pic1.jpg" /><p><b>2012</b> something</p></li>
    <li><img src="pic2.jpg" /><p><b>2016</b> something else.</p></li>
</ul>

JQuery的:

var imW=[];
var imH=[];
//...
$('li',obj).each(function(index){ 
    itemSources.push( $(this).find('img').attr('src') );                
    var img = $(this).find('img'); 
    imW.push(img.width());
    imH.push(img.height());
});

然后,我使用itemSources[i]imW[i]imH[i]調整圖像的大小,並添加任何必要的填充以將其在框架中居中。

只要我的互聯網足夠快並且在計算尺寸之前加載圖像,該方法就可以正常工作。 (哈!)

我知道我想要類似的東西:

var img = new Image();
img.onload = function() {
    console.log(this.width + 'x' + this.height);
};
img.src = $(this).find('img').attr('src');

但是我無法保存寬度和高度,因為僅推送到數組會超出范圍,因此創建一個外部回調也是如此。 如何將那些容易打印到控制台的尺寸保存到我的imW和imH陣列中?

您基本上可以設置圖像的屬性,例如,一旦圖像被加載,就可以像data-loaded="true" ,當最后一個圖像被加載時,您可以對圖像進行迭代並加載數組。

onload方法中,進行以下更改

var img = new Image();
img.onload = function() {
    console.log(this.width + 'x' + this.height);

    //set this attribute to indicate that this image has been loaded already
    $(this).attr( "data-loaded", "true" );

    //check if all images have this attribute
    if ( $( "img[data-loaded='true']" ).size() == $( "img" ).size() ) 
    {
      //now iterate the images to load your array
    }
};
img.src = $(this).find('img').attr('src');

暫無
暫無

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

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