【问题标题】:Internet Explorer adds height- and width-attributes to a newly appended image automaticallyInternet Explorer 自动为新添加的图像添加高度和宽度属性
【发布时间】:2013-09-26 04:56:52
【问题描述】:

我在将新创建的图像加载到 DOM 后附加它:

var i = $('<img/>');
i[0].src = 'http://placehold.it/700x300';
i.attr('alt', '');
i.on('load', function() {
    $('body').append(i);            
});

我在 CSS 中为图片设置了固定高度:

img {
    height: 150px;
}

不幸的是,Internet Explorer 将width- 和height- 属性添加到图像中,因此图像严重失真。我怎样才能防止这种情况?附加元素后是否必须手动删除属性?

jsFiddle link

【问题讨论】:

  • IE 不向标记添加标签,是别的东西在做。
  • 只需添加宽度! jsfiddle.net/aEaEN
  • @TravisO 如果你检查你看到的小提琴,那是在 IE 中设置的属性。
  • @codeiz 是的,宽度设置为自动就可以了。我确信我测试过它,但我必须以某种方式错过它。我无法设置固定宽度,因为宽度未知。
  • IE 不添加属性,但它会缩放图像,因此不会保留宽高比。

标签: javascript jquery css internet-explorer


【解决方案1】:

您可以将 !important 添加到您的 CSS,或删除宽度和高度属性。

img {
    height: 150px !important;
}

i.height('').width('');

【讨论】:

    【解决方案2】:

    试试这个:

    img {
        height: 150px;
        width: auto;
    }
    

    【讨论】:

    • 我很确定我在询问之前对此进行了测试。工作正常。 :D 谢谢。
    • 很高兴为您提供帮助! :) 如果您觉得有帮助,请记得采纳答案。
    • 是的,我只是在等计时器。 ;)
    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2011-03-10
    • 2011-04-02
    • 2014-10-02
    • 2016-10-15
    • 1970-01-01
    相关资源
    最近更新 更多