Javascript 图像在 IE 中的行为不同

标签 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 之后/之前将尺寸设置为未定义或 0,但随后图像无法呈现。

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

注意:问题并未显示在 SO 代码段中,而是显示在 jsfiddle 上以及本地 html 文件。

编辑:图像在 Firefox/Chrome 中的样子如下:

enter image description here enter image description here

这是在 IE11 中:

enter image description here enter image description here

最佳答案

because it seems like IE sets the width and height attributes of a dynamically created image

好吧,我不会那样说。我宁愿说,尝试通过使用 $(image) 将 JS Image 元素“制作”成可追加的 HTML 代码似乎在这里有这个意想不到的结果 - 但是代码一开始对我来说看起来“很奇怪”。

一旦你用一个简单的替换它

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

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

关于Javascript 图像在 IE 中的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41923879/

相关文章:

c# - 单击时如何使内容切换向下/向上滑动

javascript - 在站点加载时运行 javascript

javascript - 通过JQuery改变背景图片

javascript - Uncaught ReferenceError : Gallery is not defined in js

jquery - 单击另一个选项卡后,Bootstrap 选项卡消失

jquery - 使用 PDO、CSS 和 JQUERY 的数据表问题

javascript - 如何在 Angular 中使用ng-template?

javascript - jQuery(formElement).val(null) : inconsistent results in different browsers

javascript - Window.getComputedStyle does not implement interface Element 错误在 Firefox 中

javascript - jQuery 颜色选择器单击时更改颜色