javascript - 如何模拟背景大小 : cover on <img>?

标签 javascript jquery math background-size

我如何调整框内图像的大小和位置,使其覆盖整个框,类似于 background-size: cover 的工作方式。

<div class="box" style="width: 100px; height: 100px;">
  <img src="pic.jpg" width="413" height="325">
</div>

我知道我必须将 overflow:hidden 添加到框中并且图像需要 position: absolute。但是,让我获得正确的图像新尺寸和左侧 + 顶部位置的公式是什么?

最佳答案

它的值(value):现在可以单独使用 CSS 来完成...

新的 CSS 属性 object-fit ( Current browser support )

只需在 img 上设置 object-fit: cover;

您甚至不需要将 img 包装在 div 中!

FIDDLE

img {
  width: 100px;
  height: 100px;
}
.object-fit {
  display: block;
  object-fit: cover;
}
.original {
  width: auto;
  height: auto;
  display: block;
}
<img src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Img 'squashed' - not good</p>
<img class="object-fit" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>object-fit: cover -
   The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible. </p>
<img class="original" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Original ing</p>

您可以在 webplatform article 中阅读有关此新属性的更多信息.

还有,这里是a fiddle来自上面的文章,它演示了 object-fit 属性的所有值。

关于javascript - 如何模拟背景大小 : cover on <img>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38243886/

相关文章:

javascript - 在 Bootstrap 中隐藏/显示卡片

javascript - 检查图表值输入的字符串值的多个 JSON 属性

JQuery增量搜索

javascript - 在 jQuery 中卡住表头

javascript - jquery中图像之间的间隔

python - 使用随机数列表和所有简单的数学运算符计算所有可能的组合以达到给定目标

algorithm - 直线多边形相交

javascript - 从 Angular 4 的数组列表中删除错误的项目

javascript - 从墙点定义 "inside room point"

javascript - 将配置值传递到 JS 文件