Javascript图像在IE中表现不同

时间:2017-01-29 17:34:23

标签: javascript jquery css internet-explorer

在IE 11中,图像缩放不正确,因为IE似乎设置了动态创建图像的宽度和高度属性,而Firefox / Chrome则没有。

$(function() {
    var image = new Image();
    image.src = "http://placehold.it/350x1200";
    $("div").append($(image));
})
div {
  width: 100px;
  max-height: 100px;
}

img {
  max-width: 100%;
  max-height: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
</div>

我尝试在设置src之后/之前将尺寸设置为undefined或0,但之后图像不会渲染。

如果不对IE进行额外检查,如何实现跨浏览器的一致性?有没有办法在正确的时间删除宽度/高度属性,以便它适用于所有浏览器,无论图像是否被缓存?另外,我可能事先不知道图像尺寸。

注意:问题不在SO代码段中显示,而是在jsfiddle和本地html文件中显示。

编辑:这是Firefox / Chrome中的图片:

enter image description here enter image description here

这是在IE11中:

enter image description here enter image description here

2 个答案:

答案 0 :(得分:0)

更改

img {
  max-width: 100%;
  max-height: inherit;
}

img{width:100%}

要停止子元素溢出或调整父div的高度,请添加overflow:hidden;统治div。否则,图像将以与其自然值不同的宽高比渲染,看起来很奇怪。

答案 1 :(得分:0)

  

因为IE似乎设置了动态创建的图像的宽度和高度属性

好吧,我不会这么说。我宁愿说,试图通过使用Image将JS $(image)元素“制作”成可附加的HTML代码似乎在这里出现了意想不到的结果 - 但是这段代码对我来说看起来很“奇怪”用。

用简单的

替换它
$("div").append('<img src="http://placehold.it/350x1200">');

IE 11显示的图像与其他浏览器相同。