javascript - 获取未知图像的大小并更改类别

标签 javascript html css image tumblr

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

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;
}

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

最佳答案

您的想法是正确的,但是您使用的特定 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
   }
 });

关于javascript - 获取未知图像的大小并更改类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30786509/

相关文章:

javascript - Vue.js 来自多个搜索项的粗体术语

javascript - 数据表 : add row and check added row's index

javascript - 无法下载 HTML Canvas 上的图像

Javascript 函数从 HTML 事件运行但从 IF 语句失败

html - 背景图片 url 链接问题

css - 自定义字体在浏览器中更改

html - 使用清除 :both to make div full height of content?

array.pop() 上的 JavaScript 错误?

html - 将 2 个输入字段与下拉 Bootstrap 对齐

html - 使用 CSS 对齐两个元素