2016-07-25 42 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);