2013-03-14 109 views
1

今天我試圖操縱圖像時遇到了IE8的一個有趣的情況。IE8 jQ設置CSS屬性(寬度或邊距)被忽略

我正在更換加載的圖像通過更改它們的URL和它們何時加載我試圖正確地擠壓它們並以視口元素爲中心(新圖像不像前輩那樣是正方形)。 但在IE8(沒有測試IE7,並從同事那裏聽到IE9 - 是所有罰款)圖像不按比例,他們只是下降的原始大小和我

img.height(105); 
img.css('margin-left', (shift?-shift:0)); 

被簡單地忽略。 這裏是代碼與問題剪斷。

$('.people-images img').each(function() { 
     var img = $(this); 
     var oUrl = img.attr('src'); 

     oUrl = oUrl.replace(/[SM]Thumb/, 'LThumb'); 

     img.bind('load', function() { 
      var img = $(this); 
      if (this.width > this.height) { 
       var shift = (this.width/(this.height/105) - 105)/2; 
       img.height(105); 
       img.css('margin-left', (shift?-shift:0)); 
      } 
      else { 
       var shift = (this.height/(this.width/105) - 105)/2; 
       img.width(105); 
       img.css('margin-top', (shift?-shift:0)); 
      } 
     }); 

     img.attr('src', oUrl); 
     img.attr('style', null); 
     img.parent().attr('style', null); 
    }); 

請查看我的自我解答。

回答

1

問題原來是IE圖像緩存和它處理事件處理程序的方式。 css在這條線上被我自己清除img.attr('style', null);。因此,簡單地將這種樣式刪除解決了問題。

$('.people-images img').each(function() { 
    var img = $(this); 
    var oUrl = img.attr('src'); 

    oUrl = oUrl.replace(/[SM]Thumb/, 'LThumb'); 
    img.attr('style', null); 

    img.bind('load', function() { 
     var img = $(this); 
     if (this.width > this.height) { 
      var shift = (this.width/(this.height/105) - 105)/2; 
      img.height(105); 
      img.css('margin-left', (shift?-shift:0)); 
     } 
     else { 
      var shift = (this.height/(this.width/105) - 105)/2; 
      img.width(105); 
      img.css('margin-top', (shift?-shift:0)); 
     } 
    }); 

    img.attr('src', oUrl); 
    img.parent().attr('style', null); 
}); 

我覺得這很奇怪,因爲即使高速緩存圖像確實會立即加載怎麼來的IE觸發回調的執行範圍的中間?

猜測,在src替換之前放置樣式相關代碼也應該可行,但我沒有證實。

img.attr('style', null); 
img.attr('src', oUrl); 

希望這會有所幫助!