html - 缩放具有多个宽度和高度约束的图像

标签 html css responsive-design

我有一个简单的网站/html 页面,应该显示一张图片和一些按钮。但图片大小应遵循以下规则:

  • 图像的较短边不应显示为超过 600 像素
  • 图像高度应最大为窗口的 80%,以便在无需滚动的情况下为 UI 留出空间
  • 图像宽度应达到窗口的 100%
  • 图片不应放大显示
  • 图片的纵横比不应改变

关于较小尺寸的规则:较短尺寸是指图像的高度或宽度(以像素为单位),具体取决于哪个数量较小。因此,如果图像为 2000x1200,则应以 1000x600 显示,因此较短的尺寸为 600。而且 1200x88888 的图像将显示为 600x44444 像素。

这是我尝试过的。我调整了所有图像的大小,以便它们的较短尺寸为 600 像素或更短。但是图像仍然是多种多样的,图像可以是 3000x600,也可以是 100x3000 或 100x100。

在我试过的代码中:

<div style="max-height: 80%">
  <img style="margin: 0px auto; display: block; height: 100%;" src="http://www.dummyimage.com/800x200/000/fff&text=image">
</div>

但这对我不起作用,因为如果 80% 的窗口高度大于图像,图像会变大。

这里有一个 30% 的 fiddle ,而不是 80%,以使其更容易看到:http://jsfiddle.net/ErNeT/2723/

最佳答案

如果没有 JavaScript(确定短边),可能无法确定图像是纵向还是横向。所以:

$(window).on("load", function() {
  $("img").each(function() {
    if (this.naturalWidth >= this.naturalHeight) {
      $(this).addClass("landscape");
    } else {
      $(this).addClass("portrait");
    }
  });
});
body {
  margin: 0;
}
.demo {
  position: relative;
  height: 100vh;
  background-color: peachpuff;
}
.demo:nth-of-type(even) {
  background-color: papayawhip;
}
.demo::before {
  position: absolute;
  content: attr(title);
}
/* style used on page load */
img {
  max-width: 100vw;
  max-height: 80vh;
}
/* classes added by JavaScript */
img.landscape {
  max-width: 100vw;
  max-height: 600px;
}
img.portrait {
  max-width: 600px;
  max-height: 80vh;
}
/* 600px is greater than 80vh for screen shorter then 750px so... */
@media screen and (max-height: 750px) {
  img.landscape {
    max-height: 80vh;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="demo" title="Shorter side test (landscape)">
  <img src="http://www.dummyimage.com/1000x700/ccc/000"></div>

<div class="demo" title="Shorter side test (portrait)">
  <img src="http://www.dummyimage.com/700x1000/ccc/000"></div>

<div class="demo" title="Viewport width and height test">
  <img src="http://www.dummyimage.com/2400x2400/ccc/000"></div>

<div class="demo" title="No stretch test">
  <img src="http://www.dummyimage.com/200x200/ccc/000"></div>

关于html - 缩放具有多个宽度和高度约束的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52272613/

相关文章:

jquery - 知道复选框是否被选中的正确方法

html - 对齐子菜单

css - 高分辨率屏幕上的网站太小

c# - 如何使用 selenium C# 清除 session 存储?

html - 横幅落下后,删除 Logo

javascript - 使用Javascript向服务器发送多个请求,直到服务器返回200

css - 使用 CSS 和图像生成 PDF

Javascript 样式显示无法正常工作

html - 我怎样才能使网格(设计)响应?

html - 可折叠导航栏未按预期工作并创建不必要的填充(不使用 Bootstrap )