我其实解决了这个问题的Wi日这个插件:
//Scale and offset an image to fill its container
(function($) {
$.fn.scaleImageToFillParent = function(){
//Scale and offset
$(this).bind('reposition', function(){
//Vars
var $this = $(this);
var $parent = $(this).parent();
//Save natural width/height
if(typeof($this.data('scaleImageToFillParentSetup')) == 'undefined') {
$this.data('scaleImageToFillParentSetup', true);
if ('naturalWidth' in (new Image)) {
$this.data('naturalWidth', $this[0].naturalWidth);
$this.data('naturalHeight', $this[0].naturalHeight);
} else {
var img = new Image;
img.src = $this.attr('src');
$this.data('naturalWidth', img.width);
$this.data('naturalHeight', img.height);
}
$this.data('aspectRatio', $this.data('naturalWidth')/$this.data('naturalHeight'));
$(this).css({
maxWidth: 'none',
minWidth: 0,
maxHeight: 'none',
minHeight: 0,
position: 'absolute',
top: 0,
left: 0
});
$(this).addClass('active');
//Emergency! Somebody didn't wait 'til the image had loaded!
if(typeof($this.data('naturalWidth')) != 'number' || $this.data('naturalWidth') == 0) {$this.removeData('scaleImageToFillParentSetup');}
}
//Get dimensions of container
var contWidth = $parent.width();
var contHeight = $parent.height();
var contRatio = contWidth/contHeight;
var imgRatio = $(this).data('aspectRatio');
if(imgRatio > contRatio) {
//Fit so height 100%
var newImgWidth = contHeight * imgRatio;
$(this).css({
width: newImgWidth,
height: contHeight,
marginTop: 0,
marginLeft: (contWidth - newImgWidth)/2,
});
} else {
//Fit so width 100%
var newImgHeight = contWidth/imgRatio;
$(this).css({
width: contWidth,
height: newImgHeight,
marginTop: (contHeight - newImgHeight)/2,
marginLeft: 0
});
}
});
$this = $(this);
$(window).load(function(){$this.trigger('reposition');}).resize(function(){$this.trigger('reposition');});
}
})(jQuery);
借口格式
,但你这样称呼它:
$('img.hero_image').scaleImageToFillParent();
嗨, 我需要的图像,以填补像HMV网站 – saunders
整个容器@ user720414:你需要支持比IE9更早的任何东西吗?你能切换到使用“背景图像”吗?如果是这样,'background-size:cover'应该可以工作。 http://jsfiddle.net/LwJ2C/3/ –
我确实需要支持ie8向上,但我试过背景大小:封面,但仍然没有给我的问题相同的影响,我给我的问题 – saunders