2012-06-30 43 views
8

我正在嘗試使圖像拉伸以適合div內。不過,我希望它溢出,以便整個div被填滿。 div調整頁面大小。我想要一個類似於jQuery bgstretcher插件(http://www.ajaxblender.com/bgstretcher-2-jquery-stretch-background-plugin-updated.html)的效果,但我無法使用該插件,因爲我已經將它用於頁面上的背景圖像,並且當您嘗試激活它的多個實例時似乎不起作用。拉伸圖像填充div,但不扭曲

所以我問的是某種簡單的jQuery函數,它調整圖像的大小以便完全填充隱藏溢出的div,這樣就沒有間隙,但不會使圖像傾斜。

編輯:

http://jsfiddle.net/R7UCZ/

這是那種我後,但我想要的形象填補整個DIV 沒有傾斜。如果圖像超出了div的範圍,那很好,但是我需要用div來調整大小,div的高度和寬度都與頁面大小有關。

回答

9

首先,你需要獲取圖像的屬性,看看哪一個更大,高度或寬度,然後調整基礎上,格大小圖像的窗口大小調整後,像這樣:

//this would load up initially, you will need this data for future processing 


    div = $("div"); 
    imgsrc = div.find('img').attr('src'); 

    var img = new Image() 
    img.onload = function(){ 
     imgw = img.width; 
     imgh = img.height; 

     //after its loaded and you got the size.. 
     //you need to call it the first time of course here and make it visible: 

     resizeMyImg(imgw,imgh); 
     div.find('img').show(); 

     //now you can use your resize function 
     $(window).resize(function(){ resizeMyImg(imgw,imgh) }); 

     } 
    img.src = imgsrc 


    function resizeMyImg(w,h){  
     //the width is larger 
     if (w > h) { 
     //resize the image to the div 
     div.find('img').width(div.innerWidth() + 'px').height('auto'); 
     }   
     else { 
     // the height is larger or the same 
     //resize the image to the div 
     div.find('img').height(div.innerHeight() + 'px').width('auto'); 
     } 

    } 

你實際上可以在這裏找到一個完整的解決方案: http://jsfiddle.net/CDywS/1

+0

是的!謝謝! – r0tterz

0

您可以簡單地這樣做:

<img src="your_picture.png" alt="" style="width:100%;height:100%"></img> 

當你的div容器調整圖像大小將伸展自己,以填補整個股利。

編輯:

如果你不希望圖像歪斜:

<img src="your_picture.png" alt="" style="width:100%"></img> 

或者:

<img src="your_picture.png" alt="" style="height:100%"></img> 

取決於哪個維度你不想溢出...

+0

我試圖讓整個圖像填補了** **出**偏差。所以如果圖像的邊緣離開div有點不錯,只要它不歪斜。 – r0tterz

+0

我編輯了我的答案,告訴你如何輕鬆實現... –

6

根本不需要JavaScript/jQuery。只需使用containcoverbackground-size

  1. background-size: contain縮放圖像到它的最大寬度/高度,使整個圖像是可見的,同時保持高寬比。 (無溢出)

  2. background-size: cover將圖像縮放到最大寬度,以便在保留寬高比的同時使整個div充滿圖像。(溢出,如果圖像是不是方形)

因此,你只需要編寫代碼:

#myDiv { 
    background-size: contain; 
} 

或者:

#myDiv { 
    background-size: cover; 
} 

的更多信息:http://css-tricks.com/perfect-full-page-background-image/

更新Demo

+0

但它不是一個背景圖像。那好極了!我不知道,但它是一個圖像*裏面*一個div。 – r0tterz

+0

也許你可以在jsfiddle.net上創建一個演示,這樣我就可以更清楚地看到你正在嘗試做什麼 – Alp

+0

雖然我可以讓它們變成div ...... hm ... – r0tterz

1

Zee Tee的答案被標記爲正確,它確實做了這項工作 - 但只適用於橫向圖像。縱向圖像無法使用它,正如您可以看到的,如果您在jsfiddle示例中嘗試這樣的圖像。

但是,您可以通過將包含圖像的div設置爲高度來使其工作。你可以給這個或者一個最小高度設定一個固定值,或者可以工作。

這樣做的原因是,在resizeMyImg功能,在線路:

div.find('img').height(div.innerHeight() + 'px').width('auto'); 

div.innerHeight是未定義的,除非div有與之相關聯的高度或最小高度的CSS屬性。