2

我有一个垂直滚动照片库的问题,我希望调整垂直图像的大小,但水平图像就可以了。水平图像的宽度为 900 像素,而垂直图像对于舒适的屏幕观看来说太高了,所以我想要两个 440 像素宽度的垂直图像和 20 像素的中心边距以适应一个水平图像。

该网站在 Cargocollective 上,所以我不能使用 PHP,只能使用 Jquery、Javascript 和 CSS 而且我只能添加 HTML。有人有解决方案吗?

一种检测图像比例然后仅在高度>宽度时调整大小的方法

谢谢

4

2 回答 2

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.
    }
});
于 2012-08-26T23:55:10.030 回答
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.
    }
});
于 2012-08-27T00:02:26.707 回答