我可以用html或css进行图像方向检测吗?

时间:2013-03-08 20:58:19

标签: html css html5 css3

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

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

非常感谢!

1 个答案:

答案 0 :(得分:11)

不,这是不可能的 - 条件语句不能用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>