2014-11-09 82 views
0

我創建了一個函數來使用jQuery來集中我的<div>,它在頁面加載時工作,但不在頁面調整大小。爲什麼我的函數不能在.resize()上運行?

我在做什麼錯?

JS:

<script> 
    $(document).ready(function() { 
     function reCenter() { 
      $('.content').css({ 
       position:'absolute', 
       left: ($(window).width() 
        - $('.content').outerWidth())/2, 
       top: ($(window).height() 
        - $('.content').outerHeight())/2 
      });    
     } 
     $(window).resize(reCenter()); 
     // To initially run the function: 
     reCenter(); 
    }); 
</script> 

HTML:

<div class="content"> 
    <h1>Header</h1> 
    <span class="hyphen">-</span> 
    <h2>Subtext</h2> 
</div> 

CSS:

* { 
      padding: 0; 
      margin: 0; 
     } 
     html { 
      background: darkgrey; 
     } 
     body { 
      color: #fff; 
      text-align: center; 
      /*padding-top: 300px;*/ 
     } 
     h1 { 
      font-family: 'Arimo', sans-serif; 
      text-transform: uppercase; 
      font-weight: bold; 
      font-size: 40px; 
     } 
     span.hyphen { 
      color: #0CFFFC; 
      font-size: 3em; 
     } 
h2 { 
      font-family: 'Montserrat', sans-serif; 
      font-weight: 100; 


     } 

UPDATE
讓網頁加載火起來的功能後,它的頁面加載和窗口之間存在一些不一致的行爲調整 http://jsfiddle.net/7zqkd4w8/

+0

如果您的內容不是動態的,你可以嘗試使用方法[這裏](http://www.wpdfd.com/editorial/thebox/deadcentre4.html),其中中心塊垂直和水平 – yoavmatchulsky 2014-11-09 08:58:43

回答

4

應該$(window).resize(reCenter);因爲你發送一個函數調用的不是結果功能。

+0

當我這樣做時,在調整大小函數被調用,但現在該函數不加載頁面時調用。我嘗試將最後一行改爲'reCenter;'但這也不起作用。 – Imran 2014-11-09 03:46:05

+1

保留最後一行。 – j08691 2014-11-09 03:59:52

0

你應該這樣做:

$(window).on('resize',function(){ 
    reCenter() 
}).resize();//triggers on first page load 
1

你正在努力尋找 '內容' DIV的寬度。除非它的浮動或絕對值,否則你將無法獲得div的正確寬度。您正在給reCenter()中的.content絕對類。所以如果你觸發你的調整大小功能兩次(第一次)它會起作用。

$(window).on('resize',function(){ 
    reCenter() 
}).resize().resize(); 

但建議的方法做它只是增加浮動留給內容和您現有的代碼應工作。

.content{ 
    float:left; 
} 
相關問題