【问题标题】:Add css to all img with same class with jQuery使用 jQuery 将 css 添加到所有具有相同类的 img
【发布时间】:2018-04-24 23:08:52
【问题描述】:

我有 4 个 div,其中包含图像,我需要根据 img 的宽度和高度添加一个类属性。

这是一个示例代码来解释我需要做什么。 (显然,这段代码不起作用)

function cropImg(){
  var imgs = document.getElementsByClassName(".prodImg");
  for(i in imgs){   
    var imgWidth = imgs[i].naturalWidth;
    var imgHeight = imgs[i].naturalHeight;

    if(imgWidth>imgHeight){
      imgs[i].css({
        "max-height": "100%"
      });
    }else{
      imgs[i].css({
        "max-width": "100%"
      });
    }   
  }
}

非常感谢您的帮助。

【问题讨论】:

  • 请从 div 中添加一些 html,您的功能看起来像调整图像大小,而不是裁剪它,您能说明一下您到底需要什么吗?

标签: jquery


【解决方案1】:

jQuery .each() 是你的朋友

确定图像真实大小的问题在于它可以在网站页面上调整大小。 并且 jquery 函数只给出浏览器上的尺寸,而不是它们的实际大小。

对于我的解决方案,我建议将图像的维度精确到它们的真实大小,以知道它们的值以替换初始值。

PS:宽度或高度为 100%,在任何时候都不起作用,因为它给出了父元素的大小,很少有真正的大小。

我之前测试过这段代码,但是有可能层次css中的一些约束可以把他的一粒沙子。

$("div img").each(function( index ) {
    var
    sav_h = $(this).height(),
    sav_w = $(this).width(),
    real_h = 0,
    real_w = 0;

    $(this).css({width:'auto', height:'auto'});

    real_h = $(this).height(),
    real_w = $(this).width();

    $(this).height(sav_h).width(sav_w);
    console.log( index + "       h=" + real_h + '     w=' + real_w );
});

【讨论】:

    【解决方案2】:
    function cropImg() {
        $('.prodImg').each(function() {
            var isWider = $(this).outerWidth() > $(this).outerHeight();
            isWider ? $(this).css({'max-height':'100%'}) : $(this).css({'max-width':'100%'})
        })
    }
    

    【讨论】:

      【解决方案3】:

      这不是最佳实践或最佳解决方案;只是一些简单的开始和调整。

      $(function () {
      
          cropImg();
      
          function cropImg() {
      
              var imgs = $(".prodImg");
              imgs.each(function (index, element) {
                  var imgWidth = $(this).width();
                  var imgHeight = $(this).height();
                  if (imgWidth > imgHeight)
                      $(this).css({
                          "height": "100%",
                          "width": "auto"
                      });
                  else
                      $(this).css({
                          "width": "100%",
                          "height": "auto"
                      });
      
              });
      
          }
      
      });
      

      正确裁剪和调整图像大小并保持纵横比; check this demo.

      或者这个stack answer

      【讨论】:

      • 非常感谢,这正是我想要的。 ;)
      猜你喜欢
      • 2018-04-30
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多