LoginSignup
9
10

More than 5 years have passed since last update.

指定領域内いっぱいに画像をアスペクト比を変えずに表示する

Last updated at Posted at 2015-10-29

指定領域内いっぱいに、画像をアスペクト比を変えずに表示させます。
ルールは、
横長の画像は中央を縦一杯に表示、
縦長の画像は上部を横一杯に表示です。
小さい画像も引き延ばします。
2015-10-30_00h41_39.png

html
<div class="selector">
<img src="hoge1.jpg">
</div>
<div class="selector">
<img src="hoge2.jpg">
</div>
<div class="selector">
<img src="hoge3.jpg">
</div>
css
.selector{
    width:300px;
    height:200px;
    overflow:hidden;
    position:relative;
}

.selector img{
    opacity: 0;
    position:absolute;
}


javascript
$(function(){
var fitImage = function(){

    var o = {h : $(this).height(), w : $(this).width()};
    var p = {h : $(this).parent().height(), w : $(this).parent().width()};

    if(p.h / p.w > o.h / o.w){
        $(this).css({height : p.h, left : (o.w * p.h / o.h - p.w) / -2});
    }else{
        $(this).css({width  : p.w,  top : 0});
        //中央を表示したい場合は下記   
        //$(this).css({width  : p.w,  top : (o.h * p.w / o.w - p.h) / -2});
    }

    $(this).css({opacity : 1});
};

$('.selector img').on('load', fitImage);
});
9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10