2012-12-25 65 views
0

什麼是使用CSS2來模擬即將到來的CSS3物件適合屬性的最佳方法& JS?我對包含&覆蓋方法感興趣。適合img在div容器中

編輯:在CSS3中有這裏描述的新對象適合機制:http://dev.opera.com/articles/view/css3-object-fit-object-position/但在Opera瀏覽器之外尚不支持對象適合。要創建便攜式解決方案,我需要使img增長或縮小到其父級的大小div,而不會丟失圖像的原始高寬比。這可以通過包含整個圖像(技術也稱爲letterboxing)或通過放大圖像溢出來實現,直到最小尺寸匹配div的尺寸(技術也被稱爲覆蓋)。有幾個jquery imagefit庫,因爲它們很麻煩(也許它們只在特定瀏覽器的特定情況下工作)。

編輯2:這個問題已經被那些花時間閱讀的人理解了,一個很好的答案已經被提出並且已經給出了答案。很難理解關閉它的決定。

回答

3

任何有興趣,這裏是實際可行的解決方案:

JSFiddle Demo

和實際代碼:

(function($) { 
    $.fn.imagefit = function(contain) { 
    this.each(function() { 
     var $this   = $(this), 
      $wrapper  = $this.parent(), 
      wrapper_width = $wrapper.width(), 
      wrapper_height = $wrapper.height(), 
      wrapper_ratio, 
      image_ratio; 


     // ratios 
     image_ratio = $this.width()/$this.height(); 
     wrapper_ratio = wrapper_width/wrapper_height; 

     var ratio_cond = wrapper_ratio > image_ratio; 
     if(contain) { 
      ratio_cond = !ratio_cond; 
     } 

     if (ratio_cond) { 
      $wrapper.css({ 
      'background' : 'url('+$this.get(0).src+')', 
      'background-size' : '100% auto', 
      'background-position' : '0px 50%', 
      'background-repeat' : 'no-repeat' 
      }); 
     } else { 
      $wrapper.css({ 
      'background' : 'url('+$this.get(0).src+')', 
      'background-size' : 'auto 100%', 
      'background-position' : '50% 0px', 
      'background-repeat' : 'no-repeat' 
      }); 
     } 

     $this.remove(); 

    }); 
    return this; 
    }; 

    $('div.bgthumb#cover > img').imagefit(false);    
    $('div.bgthumb#contain > img').imagefit(true);    

}(jQuery));​ 

@Hippocrates:非常感謝指着我在正確的方向。

+0

您也可以使用'ratio_cond'在wrapper元素上設置一個類,然後相應地應用樣式:'width:100%; height:auto;'或者反過來,並用'top:50%;剩下:50%;變換:翻譯(-50%,-50%);'。 – daniels

+0

我用你的解決方案,並改進了一下,以回答[類似問題](http://stackoverflow.com/a/30242945/2270233)。 – daniels

5

爲什麼使用JavaScript或CSS3的東西?只需使用這一點,你是好去

Demo

img { 
    max-width: 100%; 
    max-height: 100%; 
} 
/* This will resize you image according to the container size and 
    will retain the aspect ratio too */ 
+0

任何解釋-1? –

+0

不知道爲什麼投票..這是一個體面的解決方案艾莫。唯一的一點是,它不會超出圖像的原始大小 – dakdad

+0

@dakdad亞,但它是適合在div容器中的img,否則他可以簡單地使用'background-size:cover;' –

0

這是另一種方式 - 不使用背景圖像。 (注意,我對這個階段的定位並不擔心)

http://jsfiddle.net/Z5Hb8/2/

$('.resize').each(function(){ 
var el = $(this).find('img'), 
    pael = el.parent(), 
    ph = pael.height(), 
    pw = pael.width(), 
    pr = pw/ph, 
    img = new Image(); 

img.src = el.attr('src'); 
img.onload = function() { 
    var w = this.width, 
     h = this.height, 
     sr = w/h; 

    if (pael.hasClass('cover')) { 
     if (pr > sr) { 
      el.width(pw); 
     } else { 
      el.height(ph); 
     } 
    } else if (pael.hasClass('contain')) { 
     if (sr > pr) { 
      el.width(pw); 
     } else { 
      el.height(ph); 
     } 
    }   
} 
});