13

如果我在 html 页面上有图像,我可以使用 html 或 css 执行以下操作吗?

当图像的宽度大于高度时,将高度设置为固定值并自动拉伸宽度;当高度大于宽度时,设置宽度和自动拉伸高度?

非常感谢!

4

1 回答 1

18

不,这是不可能的——条件语句不能用 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 代码可以很容易地重构为 vanilla 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>

于 2013-03-08T21:06:27.413 回答