[英]Scale image properly but fit inside div
我正在制作一個圖庫。 這是圖像的HTML:
<div style="width: 84%; height: 100%; float: left; text-align: center;"><img
id="mainimage" style="height: 100%;"
src="http://www.gymheroapp.com/workouts/img/spinner.gif"/></div>
<!-- Loading spinner is temp image, will be replaced by Javascript later -->
當圖像是正方形時,它可以正常工作,或者寬度不比高度多。 但是,當寬度太大時,它會斷開。 圖像溢出示例:
有沒有辦法可以檢查我的Javascript中是否有溢出? 像這樣的東西:
image.setAttribute('height', '100%')
image.removeAttribute('width')
if (image.isOverflowing()) {
image.setAttribute('width', '100%')
image.removeAttribute('height')
}
更好的是,是否有任何方法可以正確地縮放圖像但是與包含div
?
最適合:
$('img').on('load',function(){
var css;
var ratio=$(this).width() / $(this).height();
var pratio=$(this).parent().width() / $(this).parent().height();
if (ratio<pratio) css={width:'auto', height:'100%'};
else css={width:'100%', height:'auto'};
$(this).css(css);
});
編輯以說明圖像在緩存中的警告
$('img').on('bestfit',function(){
var css;
var ratio=$(this).width() / $(this).height();
var pratio=$(this).parent().width() / $(this).parent().height();
if (ratio<pratio) css={width:'auto', height:'100%'};
else css={width:'100%', height:'auto'};
$(this).css(css);
}).on('load', function(){
$(this).trigger('bestfit');
}).trigger('bestfit');
這是一個簡單的CSS解決方案:
html, body { height: 100%; }
#gallery { height: 100%; width: 100%; position: relative; }
#gallery img {
/* CSS Hack will make it width 100% and height 100% */
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
/* Maintain aspect ratio */
max-height: 100%;
max-width: 100%;
}
<div id="gallery">
<img src="http://cl.vvmonnickendam.nl/files/large/87" alt="Awesome blabla gedoe">
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.