如果我在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成为defacto标准,上述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>

08-25 13:31
查看更多