【问题标题】:How to change an img width depending on img height如何根据img高度更改img宽度
【发布时间】:2012-04-22 18:05:51
【问题描述】:

我需要根据 img 高度更改 img 宽度。 我使用了 jQuery 高度属性,但它不起作用。请在下面查看我的功能。

$(function imagesSizer(){
    var img = document.getElementsByClassName('.offer_img');
    if  ($('.offer_img').height() < 210) {
         $('.offer_img').css('width','360px')
    }
});

【问题讨论】:

  • 请定义“不起作用”。您预计会发生什么,实际会发生什么,您尝试过什么解决方法?
  • 我有 1200 像素宽度的图像,我无法更改此尺寸,但我需要将此 img 调整为 310x210 框。但是,如果我要加载的某些图像的高度确实小于 210,我需要调整它的大小。
  • 感谢您的回复。你现在已经回答了“你期望会发生什么”。你能帮我们处理剩下的部分吗?真的会发生什么?您尝试过什么解决方法?
  • 什么都没有发生,img 仍然有 1200px 宽度,我需要根据图像高度将 img 宽度更改为 310px ...
  • @ŁukaszBorawski 它如何依赖于图像高度?如果高度小于 210 像素,您当前的代码只会更改宽度,这对我来说似乎是错误的。

标签: jquery image resize height width


【解决方案1】:

你应该试试

//Wait until the DOM is ready
$(function(){
    //get all images and iterate over them
    $('.offer_img').each(function(){;
        //if the height of this img is < 210
        if  ($(this).height() < 210) {
            //set the width to 360
             $(this).width(360);
        }
    });
});

【讨论】:

    【解决方案2】:

    改变

    var img = document.getElementsByClassName('.offer_img');
    

    var img = document.getElementsByClassName('offer_img');
    

    https://developer.mozilla.org/en/DOM/document.getElementsByClassName

    【讨论】:

    • 虽然您是对的,但该行与其余代码完全无关,应该完全删除。
    【解决方案3】:

    对于单个元素,

    $( function(){
        if ( $('.offer_img')[0].height() < 210 )
            $('.offer_img').width(360);
    });
    

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      相关资源
      最近更新 更多