在我的 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/