2016-07-25 55 views
0

因此,我在Wordpress類別頁面上顯示了帶有標題和摘錄的所有帖子的flexbox網格。大多數圖像的比例相同,只有少數比例更高。我想將高圖像的最大高度響應地設置爲常規圖像的高度。網格中的每個項目都有一個imageThumb類的圖像容器。將高大圖像調整爲flexbox網格中其他圖像的大小

(function($) { 
$('.imageThumb img').each(function() { 
    var maxHeight; 
    var width = $(this).clientWidth; // Current image width 
    var height = $(this).clientHeight; // Current image height 

    // Check if the current width is larger than the max 
    if(width > height){ 
     maxHeight = $(this).clientHeight; 
     console.log(maxHeight) 
    } 

    // Check if current height is larger than max 
    if(height > width){ 
     $(this).css("height", maxHeight); // Set new height 
    } 
}); 

})(jQuery); 

我知道我用(寬度>高度)位返回太多高度。我無法突出特定圖片並獲得他們的高度,因爲內容總是在不斷變化並轉移到此博客上。

這是我的CSS與此有關。

.imageThumb { 
    overflow: hidden; 
} 

.imageThumb img { 
    width: 100%; 
} 

我不想來設置圖像的寬度和高度(我原來的解決方案),因爲網站的所有者希望太平洋島國保持對擴大窗口大小變大)。我也嘗試將圖像設置爲絕對定位並將其安裝在容器內,但似乎不適用於這種情況。不確定這個問題最好的行動方式是什麼。

在此先感謝!

+0

我相信有你的問題,但我有疑問..你爲什麼檢查寬度不足以設置所有圖像具有相同的高度? –

+0

我不確定我是否理解你的評論,但我想你是說爲什麼我不把所有的圖片都設置到一定的高度?當我需要做的是爲高個體設置最大高度時,我可以但看起來過多。 –

+0

確定這是我的意思檢查代碼 –

回答

1

嗨我不知道我是否理解得好,如果不是,請讓我看看你的鏈接。

通過我的思考方式,這代碼應該使工作

var maxHeight = 0; 

$('.imageThumb img').each(function(){ 
    var thisH = $(this).height(); 
    if (thisH > maxHeight) { maxHeight = thisH; } 
}); 

$('.imageThumb img').height(maxHeight); 

歡呼聲!

+0

這使我走向正確的道路。粘貼下面的正確代碼。非常感謝! –

0

Daebak帶我到一些MODS的正確答案。我需要設置容器imageThumb的最大高度,以使寬度與其他圖片保持一致而不會翹曲高圖片。如果它最終會削減你的照片太多,你可以嘗試評論的代碼。

var maxHeight = 0; 

$('.imageThumb').each(function(){ 
    var thisH = $(this).height(); 
    if (thisH > maxHeight) { 
    maxHeight = thisH; 
    $('.imageThumb').css('maxHeight', maxHeight); 
    //may need to change to the following if pics are getting cut off too much 
    // $('.imageThumb img').css('maxHeight', maxHeight); 
    // // $('.imageThumb img').css('width', 'auto'); 

    } 
}); 

上面的代碼是不是一切工作,我需要這麼做看到下面的代碼。反饋歡迎!

var imageThumb = document.getElementsByClassName('imageThumb'); 
var arr=[]; 
var tallArr=[]; 
//add all items to an array 
$(".imageThumb").each(function(){ arr.push($(this));}); 
//filter out all items that are taller than they are wide 
arr.filter(function(obj){ 
    if(obj.context.clientHeight > obj.context.clientWidth) { 
    tallArr.push(obj); 
    } 
}); 


//loop through the items that are tall and add a new class to them 
for (i = 0; i <= tallArr.length; i++) { 
    $(tallArr[i]).addClass('bigHeight'); 
} 
//gets first item that has a normal height and grabs it's height value 
var normalHeight = arr[0].context.clientHeight; 
//change css of bigHeight 

//sets bigHeight equal to normalHeight 
$('.bigHeight').css('max-height', normalHeight);