2014-11-09 124 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; 
} 
相关问题