如何处理IE11中偶尔错误的偏移宽度/高度

How to deal with occasionally wrong offsetWidths/Heights in IE11

本文关键字:高度 错误 偶尔 何处理 处理 IE11      更新时间:2023-09-26

假设我们有以下内容:

var img = document.getElementById('someImageTag');
img.onload = function() {
  console.log(img.offsetWidth, img.offsetHeight);
};
img.src = "/path/to/300x200.png";

在IE11中(在边缘和低兼容模式下),我通常在控制台中看到300, 200,正如预期的那样。但是,我偶尔在控制台上看到28, 32 (IE的"未找到图像"图形?)。同样,在子图像的onload事件触发后,父图像的offsetWidthoffsetHeight通常是——但不总是准确的。

在我们的应用程序中可见的表现是一个短暂的错误,其中某些元素的静态大小不正确。当子元素被拖出时,有些元素打算保留特定的大小,这取决于它们的子元素的大小。

这是已知的问题吗?是否有已知的解决方法来获得相同的值?或者,是否有我应该使用的更可靠的值(可能不包括边框/填充)?

同样有用,如果不是更有用的话:是否有办法一致地重现问题[在测试中],所以我可以确定我什么时候成功地解决了这个问题?

你没有提到你使用的是哪个版本的IE,但我知道早期版本的IE(至少6和7)有时会在缓存图像时做一些奇怪的事情。

我不能测试这个,所以请尝试一下:

function onloadHandler() {
  console.log(this.offsetWidth, this.offsetHeight);
}
var img = document.getElementById('someImageTag');
img.onload = onloadHandler;
img.src = "/path/to/300x200.png";
if( img.complete || img.readyState == "complete" ) {
  onloadHandler.call(img);
}

如何告诉当一个图像已经在IE9浏览器缓存?

我想到了两种方法。

如果你想获得源图像的实际尺寸,你可以使用自然宽度和自然高度属性,当偏移量错误时,它们将返回你正在寻找的值。

img.onload = function() {
  //For browsers that don't support naturalWidth, use offsetWidth
  var myWidth = img.naturalWidth || img.offsetWidth,
      myHeight = img.naturalHeight || img.offsetHeight;
  console.log(myWidth, myHeight);
};


如果你正在从css/样式中寻找调整后的图像大小,我建议尝试使用超时延迟该功能。似乎IE11只会在onload事件触发后立即返回不正确的值。试试这样做:

img.onload = function() {
  var myWidth = img.offsetWidth,
      myHeight = img.offsetHeight;
  //From my testing, the values IE11 returns aren't always 28 and 32
  if(myWidth < 40 && myHeight < 40){
    setTimeout( function(){
      console.log(img.offsetWidth, img.offsetHeight);
    }, 150); )
  }
};


如果您希望拥有小于40x40的图像,那么上面的If语句将不起作用。假设包含img的元素大于40x40,您可以使用naturalWidth和naturalHeight检查图像是否小于其实际大小。试试这个:

img.onload = function() {
  var myWidth = img.offsetWidth,
      myHeight = img.offsetHeight,
      natWidth = img.naturalWidth || -1,
      natHeight = img.naturalHeight || -1;
  if( myWidth < 40 && myHeight < 40 && (myWidth < natWidth || myHeight < natHeight) ){
    setTimeout( function(){
      console.log(img.offsetWidth, img.offsetHeight);
    }, 150); )
  }
};