[英]How to deal with occasionally wrong offsetWidths/Heights in IE11
假設我們有以下內容:
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
事件觸發后,父offsetHeight
的offsetWidth
和offsetHeight
通常是 - 但並不總是准確的。
在我們的應用程序中可見的這種表現形式是一種短暫的錯誤,其中某些元素的靜態大小不正確。 當子元素被拖出子元素時,某些元素旨在保留特定大小(由子節點大小決定)。
這是一個已知的問題? 是否有已知的解決方法來獲得相同的值? 或者,我應該使用更可靠的值(可能不包括邊框/填充)嗎?
同樣有幫助,如果沒有更多幫助 :有沒有辦法在測試中始終如一地重現問題,那么我可以確定何時成功解決了這個問題?
你沒有提到你正在使用哪個版本的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);
}
我有兩種方法可以做到這一點。
如果要查看源圖像的實際尺寸,可以使用naturalWidth和naturalHeight屬性,這將返回偏移錯誤時要查找的值。
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); )
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.