【问题标题】:How to get new image size after changing src in IE如何在 IE 中更改 src 后获取新的图像大小
【发布时间】:2011-11-22 23:34:01
【问题描述】:

我有一个带有微调器 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 的开发者工具中检查 DOM 属性时,即使显示的是原始微调器大小,而不是新图像的大小。
  • 在 IE 开发者工具 (F12) 中,你需要按下那个小刷新来更新 DOM

标签: javascript jquery dom resize


【解决方案1】:

好像是缓存问题。

将此添加到您的图像源网址:

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

【讨论】:

    【解决方案2】:
    <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>
    

    【讨论】:

      【解决方案3】:

      在 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);
      });
      

      【讨论】:

        【解决方案4】:

        确保您也删除了 CSS 高度和宽度:

        $('#uploaded-image').css({ height: "auto", width: "auto" });
        

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-04-03
            • 1970-01-01
            • 1970-01-01
            • 2014-11-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-08-17
            相关资源
            最近更新 更多