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 になる場合幅を 300px にリサイズした後、画像の下部 100px のみが表示されます (任意の設定)。

私がやろうとしているのは、常に画像の中央を表示することです。したがって、上記の例では、画像はピクセル 50-150 (上から) を表示します。

4

1 に答える 1

1

ページ読み込み時の画像サイズがわからないように聞こえるので、デッドセンターと JavaScript の組み合わせを使用して、必要なことを行うことができます。フローは次のようになります。

  1. デッドセンターの例のようにマークアップをセットアップします。
  2. 画像が読み込まれると、その幅と高さを取得します。
  3. image margin-left を に設定し(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 に答える