如何实现此行为http://jsfiddle.net/salman/2gWVQ/,而不是使用CSS我想使用JavaScript。
<div class="square"><img src="http://dummyimage.com/400x200/FC0/000000" class="wide">
</div>
<br>
<div class="square"><img src="http://dummyimage.com/200x400/FC0/000000" class="tall">
</div>
.square {
width: 150px;
height: 150px;
background-color: #CCC;
/* center align trick */
line-height: 150px;
text-align: center;
}
.square img {
/* center align trick */
vertical-align: middle;
}
.square .wide {
width: 150px;
}
.square .tall {
height: 150px;
}
根据链接,我希望图像调整到宽度/高度并保持比例,图像和div尺寸都是可变的。
答案 0 :(得分:0)
这似乎可以解决问题:
image.onload = function(){
var ratioWidth = div.width / image.width;
var ratioHeight = div.height / image.height;
if (ratioWidth < ratioHeight) {
image.width = div.width;
image.style.top = -((image.height - div.height) / 2) + "px";
} else {
image.height = div.height;
image.style.left = -((image.width - div.width) / 2) + "px";
}
};