简体   繁体   中英

jQuery, scaling and resizing images

I'm trying to make a images scale in a square div of size 198px with overflow:hidden

The magic class refers to an img

$('.magic').on('load', function(){
    var self = $(this);
    var width = self.width();
    var height = self.height();
    if(width>height){
        self.css('height', '198px');
        self.css('width', 'auto');
    }
    else{
        self.css('width', '198px');
        self.css('height', 'auto');
    }
});

Now the img is filling the div and not becoming bigger than it.

As in a landscape photo is not scaling perfectly but instead stretching.

See the fiddle: http://jsfiddle.net/powtac/VcLKL/19/

$(document).ready(function() {
    $(".magic").each(function(){
        var self = $(this);
        var width = self.width();
        var height = self.height();

        if(width > height){
            self.css('height', '198px');
            var ratio = width / height;
            self.css('width', 198 * ratio);
            self.css('margin-left', ((198 - parseInt(self.css('width')))/2));
        }
        else{
            self.css('width', '198px');
            var ratio = height / width;
            self.css('height', 198 * ratio);
            self.css('margin-top', ((198 - parseInt(self.css('height')))/2));
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM