2010-02-13 175 views
2

我正在爲各種尺寸的圖像創建幻燈片,以在畫布區域內垂直和水平居中顯示。在圖像上使用max-width = 100%和max-height = 100%,計算顯示寬度/高度

在我的CSS中,我將圖像的寬度和高度設置爲100%,以便每個圖像按比例填充畫布。由於圖像的原始尺寸非常大(高達800像素),因此我希望畫布自動調整尺寸以適應觀看者的屏幕尺寸。

我使用jQuery 1.4,並使用圖像的高度來計算絕對定位到畫布中間的頂部值。我已經嘗試使用jQuery來獲取.height(),innerHeight()和outerHeight(),但它總是獲取圖像的完整大小。

我從jQuery對象中提取DOM元素,並嘗試使用.width,.offsetWidth和.clientWidth,但是這似乎總是返回圖像的全尺寸。

Firebug顯示正確的尺寸,所以我知道有一些方法來計算圖像的實際顯示高度,我只是無法弄清楚它是什麼。如果您設置了max-height = 100%,您如何獲得圖像的實際顯示高度?

我不想計算和設置js中每個圖像的高度,但如果必須的話,我會的。它看起來像我應該能夠設置畫布大小,並有圖像自動調整。

+0

查看另一個帖子:http://stackoverflow.com/questions/600743/how-to-get-div-height-to-auto-adjust-to-background-size – 2010-02-13 04:06:13

回答

2

我建議將圖像恢復爲自動,然後獲取圖像值,然後將其設置回100%。

$('img').each(function(){ 
    var self = $(this); 
    self.hide() // Hide them, fading, you choose 
     .css({'width':'auto', 'height':'auto'}) // set them to auto. 
     .data('width', self.width()) // Now you can get the real size 
     .data('height', self.height()) // And store it as jQuery data in the image. 
     .css({'width':'100%', 'height':'100%'}) // Back to 100% 
     .show(); // Show them. 
}); 

,或者其他的方式

$('img').hide().css({'width':'auto', 'height':'auto'}) 
    .each(function(){ 
     var self = $(this); 
     self.data('width', self.width()) 
      .data('height', self.height()); 
    }) 
    .css({'width':'100%', 'height':'100%'}).show(); 

或者沒有必要隱瞞他們,因爲可能的變化太快了,但你可能需要做一些調整,以你的邏輯,使用戶沒有按在第一次加載期間看不到眨眼。

無論哪種方式,挑選你的毒藥。