问题:
- 调整图像大小以适合 div - 已解决
- 保持比率 - 已解决
- 水平和垂直居中 - 已解决
圆角
a) 矩形图像 - 已解决
b) 横幅图片 - !!! 不可能!!!
所以问题是:我如何摆脱图像的矩形角?请看这里看问题: >>> http://jsfiddle.net/infoman/5fzET/3/ <<<
换句话说:图像的角是圆形的,但它们不在 div 的末尾,而是在它之外。我需要将图像在 div 结束的行处四舍五入。
HTML
test image ratio w/h = 4
<div>
<img id="myimg" src='http://placehold.it/200x50' draggable="false"/>
</div>
<br/>
test image ratio w/h = 0.25
<div>
<img id="myimg" src='http://placehold.it/50x200' draggable="false"/>
</div>
<br/>
test image ratio w/h = 1 but small
<div>
<img id="myimg" src='http://placehold.it/50x50' draggable="false"/>
</div>
<br/>
test image ratio w/h = 1 perfect fit
<div>
<img id="myimg" src='http://placehold.it/300x300' draggable="false"/>
</div>
<br/>
test image ratio w/h = 1 much too big
<div>
<img id="myimg" src='http://placehold.it/2000x2000' draggable="false"/>
</div>
CSS
div {
border: solid 1px green;
width: 300px;
height: 300px;
overflow: hidden;
border-radius: 10px;
}
div img {
outline: solid 1px red;
}
.fillwidth {
width: 100%;
height: auto;
position: relative;
/*top*/
}
.fillheight {
height: 100%;
width: auto;
position: relative;
/*left*/
}
.fillfull {
height: 300px;
width: 300px;
}
jQuery
$('img[id^="myimg"]').each(function() {
var imgWidth = $(this).width(),
imgHeight = $(this).height(),
imgRatio = imgWidth / imgHeight,
imgWidthTop = (((300 / imgWidth) * imgHeight) / 2) * -1 + 300 / 2,
imgHeightLeft = (((300 / imgHeight) * imgWidth) / 2) * -1 + 300 / 2;
switch (true) {
case (imgRatio === 1):
$(this).addClass('fillfull');
break;
case (imgRatio < 1):
$(this).addClass('fillwidth');
$(this).css('top', imgWidthTop);
break;
case (imgRatio > 1):
$(this).addClass('fillheight');
$(this).css('left', imgHeightLeft);
break;
default:
break;
}
});
尝试与失败:
- 剪辑:http: //jsfiddle.net/infoman/5fzET/4/