2

画像ギャラリーを作っています。これは画像の 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か?

4

2 に答える 2

15

jqueryの例

最適:

$('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');
于 2013-01-20T14:21:50.517 に答える
7

Heres a simple CSS solution:

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>

Fiddle example

于 2013-01-20T14:30:41.463 に答える