1

我有一个包含图像的容器,并且该图像是从应用程序加载的,因此容器的尺寸是已知的,而图像会有所不同。

我目前有以下CSS:

#secondary_photos {
  height: 100px;
  width: 300px;
  overflow: hidden;
}

#secondary_photos .small_photo {
  float:left;
  height: 100px;
  width: 300px;
}

#secondary_photos .small_photo img{
  height: 100%;
  width: auto;
  position: absolute;
  bottom: 0px 
}

#secondary_photos .small_photo img{
  height: auto;
  width: 100%;
  position: absolute;
  bottom: 0px 
}

这对我来说“没问题”:它加载图像,调整它的大小以占据容器宽度的 100% 并定位它,以便图像的下半部分显示在容器内 - 所以如果图像最终是 200px high 将宽度调整为 300px 后,仅显示图像底部的 100px(任意设置)。

我想要做的是始终显示图像的中间 - 所以在上面的例子中,图像将显示 50-150 像素(从顶部)..

4

1 回答 1

1

由于听起来您不知道页面加载时的图像大小,因此您可以结合使用死点和 javascript 来执行您想要的操作。流程如下:

  1. 像死点示例一样设置标记。
  2. 加载图像时,获取其宽度和高度。
  3. 将图像左侧边距设置为(image width / 2 * -1).
  4. 将图像顶部设置为(image height / 2 * -1).

由于您可能还有比容器大的图像,因此您可以为此添加条件检查:

// Get DOM elements
var container = document.getElementById('container');
var image = document.getElementById('img');

// Check they're good
if(container && img){
  var height = image.height;
  var width = image.width;

  // Horizontally centre if container is wider than image
  if(container.offsetWidth > width){
    image.style.marginLeft = Math.floor((width / 2 * -1)) + "px";
  }

  // Vertically centre if container is taller than image
  if(container.offsetHeight > height){
    image.style.top = Math.floor((height / 2 * -1)) + "px";
  }
}
于 2011-09-26T23:52:51.267 回答