2012-08-26 51 views
2

我有一个垂直滚动照片库的问题, 我想垂直图像调整大小,但水平图像很好的方式。 水平图像的宽度为900px,垂直图像太高而不能舒适地观看屏幕,所以我想要两个440px宽度的垂直图像和20px的中心边缘以适合低于一个水平线。只调整垂直图像

该网站是在Cargcollective,所以我不能使用PHP,只有JQuery的,Javascript和CSS 而我只能在HTML上添加。 任何人都有解决方案?

以检测所述图像的比,然后才调整如果高度>宽度

由于

回答

4
$('img').each(function(i,obj){ 
    if($(obj).height() > $(obj).width()){ 
     //portrait, resize accordingly 
    }else{ 
     //landscape display; the default you want. 
    } 
}); 

jQuery的1.7以上,我们可以在不使用访问每个图像的属性的方式$ .each迭代器。

$('img').prop('height', function(){ 
    if($(this).height() > $(this).width()){ 
     //portrait, resize accordingly 
    }else{ 
     //landscape display; the default you want. 
    } 
}); 
+0

也可以使用'$(this)'而不是通过'obj'传递,但这只是我个人的偏好! – ahren

2

OhGodwhy的答案的变体,确保在计算高度/宽度时加载图像。

$('#myElement img').load(function(){ 
    if($(this).height() > $(this).width()){ 
     //portrait, resize accordingly 
     var width = $(this).width(); 
     var height = $(this).height(); 
     var newWidth = 400; 
     var newHeight = newWidth * (height/width); 
     $(this).width(newWidth).height(newHeight); 
    }else{ 
     //landscape display; the default you want. 
    } 
});