2013-01-09 54 views
0

我目前正在編程我的新網站組合。到現在爲止還挺好。我決定完全以%爲基礎,並且我正在用最後一個細節來構造:垂直居中div與基於百分比的圖像

我必須在基於%的div框中垂直居中基於%的圖像。

這裏是小提琴:http://jsfiddle.net/PX4tF/4/

這就像我希望它是不起作用的代碼:

$(document).ready(function(){ 

     $(window).resize(function(){ 

      $('.vertical_center').css({ 
      position:'relative', 
      left: ($(window).width() 
      - $('.vertical_center').outerWidth())/2, 
      top: ($(window).height() 
      - $('.vertical_center').outerHeight())/2 
      }); 

     }); 

     // To initially run the function: 
     $(window).resize(); 

     }); 

我目前只使用該腳本開始時我調整到正常工作窗戶。在此之前,這種方式會使圖像居中,但不正確。此外,我有多個div盒,如我的網頁上的小提琴盒,目前我必須複製腳本以在瀏覽器被阻止後正確居中。有沒有辦法讓這更容易?

這裏是鏈接到測試網站:http://www.zeiteffekt.de/relaunch

我不是編程的人,所以我希望你們能幫助我與此有關。

乾杯, 添

回答

1

嘗試是這樣的

function alignImage() 
{ 
    $('.vertical_center').css({ 
     position:'relative', 
     left: ($(window).width() - $('.vertical_center').outerWidth())/2, 
     top: ($(window).height() - $('.vertical_center').outerHeight())/2 
    }); 
} 
$(window).load(function() { 
    alignImage(); 
}); 
$(window).resize(function() { 
    alignImage(); 
}); 

圖像時的$(document)。就緒被稱爲是沒有準備好。使用負載代替

0

試試這個:

$(window).resize(function(){ 
     $(".img-swap").each(function() { 
      $(this).css({ 
       position:'relative', 
       marginTop: ($(this).parent().outerHeight() 
       - ($(this).outerHeight()+15))/2 
      }); 
     }); 
}); 

jsfiddle
我更換marginTop,而不是top因爲marginTop將有助於推動剛而只有top推圖像的圖像下方的文本。

+0

在調整窗口大小之前,像@TommySorensen的例子一樣,這樣做還能工作嗎?如果是的話,這是完美的。 –