【问题标题】:object-fit alternative for ie 11ie 11 的对象适合替代方案
【发布时间】:2017-09-23 05:34:55
【问题描述】:
我在div 中有一张图片。图像设置为填充屏幕并使用以下 css 从中心缩放
.backdiv img{
height:100%;
width: 100%;
display: block;
object-fit:cover;
}
在 chrome/safari/firefox 上一切正常。在 IE 11 上,图像的纵横比不会保持不变,因为图像被强制为 100% 宽度和 100% 并且 object-fit 被忽略,因为 ie 11 不支持它。
我怎样才能在 ie 11 上达到同样的效果
【问题讨论】:
-
唯一可互操作的方法(IE9 仿真和更高版本)是使用包含 div 的背景样式属性并取消
子元素。
标签:
javascript
css
internet-explorer
【解决方案1】:
您可以取消 img 元素并设置包含 div 的背景样式
<div id="divbackground" style="position:absolute;top:0;left:0;bottom:0;right:0;background-image:url(myimage.png);background-size:fill">
要使 img 元素以其“自然”纵横比呈现,只需将其宽度或高度样式指定为 100%,而不是两者都...例如。
【解决方案2】:
这是个老问题,但我也遇到了同样烦人的问题,Chrome/Edge 一切正常,但某些 css 属性在 IE11 中不起作用,
我最终使用了 HTML“figure”元素,它解决了我所有的问题。
下面的代码强制图像很好地缩小(不改变原始纵横比)。
<figure class="figure-class">
<img class="image-class" src="{{photoURL}}" />
</figure>
和 css 类:
.image-class {
border: 6px solid #E8E8E8;
max-width: 189px;
max-height: 189px;
}
.figure-class {
width: 189px;
height: 189px;
}
【解决方案3】:
最近遇到了同样的问题,这是我的解决方案:
.backdiv {
position: relative;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
.backdiv img {
position: absolute;
width: auto;
height: auto;
min-width: 100%;
min-height: 100%;
}
它看起来完全像object-fit: cover;。图片使用flex布局居中,可以通过更改justify-content和align-items来改变图片位置
【解决方案4】:
if ('objectFit' in document.documentElement.style === false) {
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll("img").forEach(function (image) {
if (image.currentStyle['object-position'] || image.currentStyle['object-fit']) {
(image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat ");
if (image.currentStyle['object-fit'])
(image.runtimeStyle || image.style).backgroundSize = image.currentStyle['object-fit'];
if (image.currentStyle['object-position'])
(image.runtimeStyle || image.style).backgroundPosition = image.currentStyle['object-position'];
image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
}
});
});
}
这是一种解决方法,可以找到所有具有 ie 的 object-fit 和 object-position 的图像