将容器中的大图像居中但保持纵横比

时间:2014-04-24 15:35:26

标签: jquery image responsive-design response

我正在尝试复制滑块图像在http://www.hmv.com上的工作方式。如果缩小屏幕尺寸,图像就像缩小但仍然保持纵横比。缩小屏幕时你会明白的。

我有一个739像素高的容器,宽度为100%。

我为你们创建了一个jsfiddle,看看我的代码是什么。

//这是我可以添加一个jsfiddle链接

sizeHeaderImg();

但是当我缩小我的屏幕时,图像并没有保持良好的比例。我的图片尺寸是1920 x 1000

我很高兴使用可以执行此操作的插件但是如果有一些事情可以指向我正确的方向,我的代码出错了会非常感激

由于

2 个答案:

答案 0 :(得分:0)

您不需要任何javascript来实现此目的:

img {
    height: auto;
    max-width: 100%;
}

.hero-image {
    height: 739px;
    width: 100%;
    overflow: hidden;
    position: relative;
}

.hero-image img {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
}

http://jsfiddle.net/LwJ2C/2/

答案 1 :(得分:0)

我实际上用这个插件解决了这个问题:

//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();