任何有興趣,這裏是實際可行的解決方案:
JSFiddle Demo
和實際代碼:
(function($) {
$.fn.imagefit = function(contain) {
this.each(function() {
var $this = $(this),
$wrapper = $this.parent(),
wrapper_width = $wrapper.width(),
wrapper_height = $wrapper.height(),
wrapper_ratio,
image_ratio;
// ratios
image_ratio = $this.width()/$this.height();
wrapper_ratio = wrapper_width/wrapper_height;
var ratio_cond = wrapper_ratio > image_ratio;
if(contain) {
ratio_cond = !ratio_cond;
}
if (ratio_cond) {
$wrapper.css({
'background' : 'url('+$this.get(0).src+')',
'background-size' : '100% auto',
'background-position' : '0px 50%',
'background-repeat' : 'no-repeat'
});
} else {
$wrapper.css({
'background' : 'url('+$this.get(0).src+')',
'background-size' : 'auto 100%',
'background-position' : '50% 0px',
'background-repeat' : 'no-repeat'
});
}
$this.remove();
});
return this;
};
$('div.bgthumb#cover > img').imagefit(false);
$('div.bgthumb#contain > img').imagefit(true);
}(jQuery));
@Hippocrates:非常感謝指着我在正確的方向。
您也可以使用'ratio_cond'在wrapper元素上設置一個類,然後相應地應用樣式:'width:100%; height:auto;'或者反過來,並用'top:50%;剩下:50%;變換:翻譯(-50%,-50%);'。 – daniels
我用你的解決方案,並改進了一下,以回答[類似問題](http://stackoverflow.com/a/30242945/2270233)。 – daniels