【问题标题】:Resize only vertical images仅调整垂直图像的大小
【发布时间】:2012-08-21 12:27:57
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: javascript jquery css image image-resizing


    【解决方案1】:
    $('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.
        }
    });
    

    【讨论】:

    • 也可以使用$(this)而不是通过obj,但这只是个人喜好我猜!
    【解决方案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.
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      相关资源
      最近更新 更多