2015-07-13 129 views
0

我有一個塊的列表div.project,每個塊包含具有不同寬度和高度的圖像。我需要將圖像的寬度和高度設置爲div.project如何設置標記包含圖像的寬度和高度

$('.project').find('img').each(function() { 
     var width = $('img').width(); 
     var height = $('img').height(); 
     $('.project').css('width',width); 
     $('.project').css('height',height); 
     }); 

問題是jquery的設定寬度和第一高度div.project每個div.project

回答

1

見這個例子:http://jsfiddle.net/kevalbhatt18/44t0aw9d/

注:您,是因爲如果指向 的.project類使用該關鍵字在你的每個環路,則寬度和高度的最後一個圖像將適用於​​。項目 類

$('.project').find('img').each(function() { 
    console.log($(this)) 
    var width = $(this).width(); 
    var height = $(this).height(); 
    console.log($($(this).parentElement)) 
    if ($(this)[0].parentElement) { 
     $($(this)[0].parentElement).css('width', width); 
     $($(this)[0].parentElement).css('height', height); 

    } 
}); 

而且insted的parentElement的可以使用.parent()

$('.project').find('img').each(function() { 
    var width = $(this).width(); 
    var height = $(this).height(); 
    $(this).parent().css('width', width); 
    $(this).parent().css('height', height); 

}); 

編輯

這是一個更多的解決方案。 http://jsfiddle.net/kevalbhatt18/44t0aw9d/2/ ,我認爲這個解決方案是好的,因爲從這個標記開始,所以它是有效的,然後是兩個以上的解決方案。

$('.project').each(function() { 
    $img = $(this).find('img') 
    var width = $img.width(); 
    var height = $img.height(); 
    $(this).css('width', width); 
    $(this).css('height', height); 

}); 

+0

我會用'最接近( '項目')',而不是'parent'作爲IMG可能不是直接孩子(如運算使用了'.find '而不是'.children') – Pete

+0

我編輯我的答案爲@Pete說** img可能不是直接的孩子**所以我現在正在從父母的孩子。 –

相關問題