HTMLページに画像がある場合、HTMLまたはCSSを使用して次のことを実行できますか?
画像の幅が高さよりも大きい場合は、高さを固定値に設定し、幅を自動ストレッチします。高さが幅よりも大きい場合、幅と自動ストレッチ高さを設定しますか?
どうもありがとう!
いいえ、これは不可能です。条件文はHTMLまたはCSSで処理できませんが、JSで処理する必要があります。
例として、画像のアスペクト比を計算(および将来の使用のために保存)して、画像が横向きモードか縦向きモードかを判断します。
$(document).ready(function() {
$("img").each(function() {
// Calculate aspect ratio and store it in HTML data- attribute
var aspectRatio = $(this).width()/$(this).height();
$(this).data("aspect-ratio", aspectRatio);
// Conditional statement
if(aspectRatio > 1) {
// Image is landscape
$(this).css({
width: "100%",
height: "auto"
});
} else if (aspectRatio < 1) {
// Image is portrait
$(this).css({
maxWidth: "100%"
});
} else {
// Image is square
$(this).css({
maxWidth: "100%",
height: "auto"
});
}
});
});
ここでフィドルを参照してください-http ://jsfiddle.net/teddyrised/PkgJG/
2019年の更新:ES6がデファクトスタンダードになりつつあるため、上記のjQueryコードは簡単にバニラJSにリファクタリングできます。
const images = document.querySelectorAll('img');
Array.from(images).forEach(image => {
image.addEventListener('load', () => fitImage(image));
if (image.complete && image.naturalWidth !== 0)
fitImage(image);
});
function fitImage(image) {
const aspectRatio = image.naturalWidth / image.naturalHeight;
// If image is landscape
if (aspectRatio > 1) {
image.style.width = '100%';
image.style.height = 'auto';
}
// If image is portrait
else if (aspectRatio < 1) {
image.style.width = 'auto';
image.style.maxHeight = '100%';
}
// Otherwise, image is square
else {
image.style.maxWidth = '100%';
image.style.height = 'auto';
}
}
div.wrapper {
background-color: #999;
border: 1px solid #333;
float: left;
margin: 10px;
width: 200px;
height: 250px;
}
<div class="wrapper">
<img src="http://placehold.it/500x350" />
</div>
<div class="wrapper">
<img src="http://placehold.it/350x500" />
</div>
<div class="wrapper">
<img src="http://placehold.it/500x500" />
</div>
ただし、画像が任意のサイズのコンテナ内に収まるようにするだけの場合は、単純なCSSを使用すると機能します。
div.wrapper {
background-color: #999;
border: 1px solid #333;
float: left;
margin: 10px;
width: 400px;
height: 400px;
}
div.wrapper img {
width: auto
height: auto;
max-width: 100%;
max-height: 100%;
}
<div class="wrapper">
<img src="http://placehold.it/500x350" />
</div>
<div class="wrapper">
<img src="http://placehold.it/350x500" />
</div>
<div class="wrapper">
<img src="http://placehold.it/500x500" />
</div>