【问题标题】:Get size of an unknown image and change class获取未知图像的大小并更改类别
【发布时间】:2015-06-11 16:35:21
【问题描述】:

在我的 Tumblr 主题中,我想为肖像图像使用不同的 CSS 类。 默认情况下,图像通过img-tag 进入并获得bilder 类。但如果是肖像图像,我想将builder 类替换为hhcoch 类。

HTML:

<img src="{..}" />

JavaScript:

    var someImg = $("img");
    if (someImg.height() > someImg.width()){
        $( "img" ).addClass( "hhoch" );
    }

CSS:

.bilder {
    height: auto; /*override the width below*/
    min-width: 100%;
    max-width: 100%;
    display: inline;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
}

.hhoch {
    min-height: 800px;
    max-height: 800px;
    width: auto;
}

总结: 如果是肖像,则图像应该得到不同的类。

【问题讨论】:

    标签: javascript html css image tumblr


    【解决方案1】:

    您的想法是正确的,但是您使用的特定 jQuery 选择器将返回文档中所有图像标签的数组。

    这意味着您需要遍历图像 DOM 节点数组并以这种方式应用您的类。

     var $images = $('.bilder');
     $images.each(function(index, img){
       if(img.height > img.width){  // is it a portrait-image?
         $(img).removeClass('bilder');  // Remove default class
         $(img).addClass('hhoch');  // Add the portrait class
       }
     });
    

    【讨论】:

    • 感谢您的回答。不幸的是,什么也没发生。
    • 啊关闭!肖像图像现在就像我想要的那样。但是风景图像(..在这种情况下..)也变小了。
    • 您是否默认添加任何一个类?还是他们只是在这个循环中上课?
    • 我已经添加了 .bilder 类,但什么也没发生。从 img 中删除所有类后,JS 代码以某种方式工作,但不仅更改了肖像图像,还更改了所有图像。
    • 好的,所以这里的目标是根据尺寸对任何具有bilder 类的图像进行重新分类?
    【解决方案2】:

    您是否尝试过将解决方案浓缩为:

    $("img.bilder").each(function(){
      if (this.height > this.width) {
          $(this).removeClass("bilder").addClass("hhoch");
      }
    });
    

    因为我认为不需要所有这些额外的代码行,这可能是您的问题。正如其他人所说,它将返回一个对象数组,因此您需要遍历它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 2019-01-21
      • 2022-01-24
      相关资源
      最近更新 更多