2013-02-22 53 views
0

目前我有一个小型项目,其中是一个响应式网站(使用Skeleton响应式网格)我使用jQuery将内容在视口中垂直居中。垂直居中的内容,除非更大

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

问题是当视口小于容器的外部宽度时,它仍然应用绝对位置。

理想情况下,我需要的东西,说

如果视口等于或大于.container的外宽度小那么不适用任何位置,但如果视大于.container应用绝对定位将其居中在视图端口?

有没有人知道如何用JQuery来实现这一点,就像我在挠头?

编辑>>>>>

将这样的事情是正确的,即时通讯样在这里救命稻草的.....

$(document).ready(function(){ 
$(window).width(); // returns width of browser viewport 
$(document).width(); // returns width of HTML document 

$(window).height(); // returns heightof browser viewport 
$(document).height(); // returns height of HTML document 

var width = $(window).width(); 
var height = $(window).height(); 

    if ((width >= 1024 ) && (height>=768)) { 
$(window).resize(function(){ 
    $('.container').css({ 
    position:'absolute', 
    left: ($(window).width() 
- $('.container').outerWidth())/2, 
top: ($(window).height() 
- $('.container').outerHeight())/2 
});  
}); 
// To initially run the function: 
$(window).resize(); 
} 
else { 
//do nothing 
} 
}); 

回答

1

使用 $(window).width(); // returns width of browser viewport$(document).width(); // returns width of HTML document 应该工作配合

if (width comparison) apply_formatting

+0

我已经添加了一个编辑你的建议,但我不知道如果我写了它正确或不。 – 2013-02-22 14:15:39

1
<script> 
$(document).ready(function(){     
    $(window).resize(function(){ 
      // Here is the new part: 
      if(($(window).width() > $('.container').outerWidth()) && ($(window).height() > $('.container').outerHeight())){ 
      $('.container').css({ 
        position:'absolute', 
        left: ($(window).width() 
        - $('.container').outerWidth())/2, 
        top: ($(window).height() 
        - $('.container').outerHeight())/2 
      }); 
      }else{ 
      $('.container').css({position:'relative'}); 
      }  

    }); 
    // To initially run the function: 
    $(window).resize(); 
}); 
</script> 

希望它有帮助。这个想法是,当两个宽度的容器的高度都小于窗口视口时,绝对定位适用,否则将应用相对(正常)定位。