【发布时间】:2016-09-20 20:28:25
【问题描述】:
基本上我想要做的是让图像填充一个 div,同时保持它们的纵横比。所以我使用 jquery 来识别它们是纵向还是横向,并从那里设置宽度或高度。
我的问题是代码提供了所有图像景观类。我不知道为什么……
谢谢!
HTML
<div class="prop">
<div class="propimage"><img src="{@image}" alt="{@prop_name}"></div>
<div class="propname">{@prop_name}</div>
<div class="propdescription">{@description}</div>
<div class="propprice">{@price}</div>
</div>
CSS
.portrait img {
width: 100%;
}
.landscape img {
height: 100%;
}
.propimage img {
display: block;
}
img {
max-width: none;
}
.propimage {
width: 100%;
height: 300px;
overflow: hidden;
float: left;
}
脚本
<script>
$(".propimage").each(function(){
// Uncomment the following if you need to make this dynamic
//var refH = $(this).height();
//var refW = $(this).width();
//var refRatio = refW/refH;
// Hard coded value...
var refRatio = 240/300;
var imgH = $(this).children("img").height();
var imgW = $(this).children("img").width();
if ((imgW/imgH) < refRatio){
$(".propimage").addClass("portrait");
} else {
$(this).addClass("landscape");
}
})
</script>
【问题讨论】:
-
什么决定什么时候应该是横向的,什么时候应该是纵向的?
-
图片的原生尺寸(我认为!)
标签: javascript jquery html css