如何在IE中更改src后获得新的图像大小

How to get new image size after changing src in IE

本文关键字:图像 src IE      更新时间:2023-09-26

我有一个带有旋转控件gif的图像元素。后来我用jQuery动态地更改了图像的src,我想获得新图像的实际宽度和高度。下面是我的代码:

function loadImage() {
$('#uploaded-image').load(function() {
    var img = document.getElementById('uploaded-image');
            // These statements return the correct values in FF and Chrome but not IE
    imgWidth = img.clientWidth;
    imgHeight = img.clientHeight;
});
$('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl);
}

这在Chrome和Firefox中工作得很好,但IE总是返回原始旋转器gif的大小,而不是新图像。

如何在IE中获得新图像的宽度和高度?

指出:

除了纯Javascript方法外,我还尝试了jQuery .width()和.height()方法,结果相同。

.load事件在所有浏览器中按预期触发

在IE中使用offsetHeightoffsetWidth

在IE中查看:http://jsbin.com/abopih/5

var imgUrl = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
 var img = document.getElementById('uploaded-image');
$('#uploaded-image').click(function() {
    imgWidth = img.clientWidth;
    imgHeight = img.clientHeight;
  $('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl);
      console.info('clientWidth: ',  img.clientWidth);
      console.info('clientHeight: ',  img.clientHeight);
      console.info('offsetWidth: ', img.offsetWidth);
      console.info('offsetWidth: ', img.offsetWidth);
});

您可以创建一个隐藏的div并将图像放置在其中以获得大小。只要确保隐藏的div没有完成display:none,因为它将没有尺寸。使用visibility:hidden,抓取尺寸,然后删除它

确保你也删除了css的height和width:

$('#uploaded-image').css({ height: "auto", width: "auto" });
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" id="file" />
<script type="text/javascript" charset="utf-8">
$("#file").change(function(e) {
    var file, img;
    file = document.getElementById("file");
    if (file!=null) {
        img = new Image();
        img.src = file.value;
        img.onload = function() {
            alert(img.width + " " + img.height);
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
    }
});
</script>

似乎是缓存问题。

添加到你的图片源url:

imgUrl += new Date().getTime();