仅调整垂直图像的大小

Resize only vertical images

本文关键字:图像 调整 垂直      更新时间:2023-09-26

我有一个垂直滚动照片库的问题,我想调整垂直图像的大小,但水平图像可以这样。水平图像的宽度为900像素,垂直图像太高,不适合在屏幕上观看,所以我想要两个440像素宽度的垂直图像和20像素的中心边距,以适合一个水平图像。

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

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

感谢

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

在jQuery1.7及以上版本中,我们可以在不使用$.each迭代器的情况下访问每个图像的属性。

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

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

$('#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.
    }
});