2013-07-25 28 views
0

我使用下面的jQuery腳本到中心窗口中間的div容器。當用戶的分辨率比容器小,因爲當網站加載div的頂部被砍掉的問題就來了。如何設置該功能只在瀏覽器大小或分辨率大於容器格時觸發?jQuery的頁面上居中的div和斬去頂部

<script> 
    $(window).load(function(){ 
     var positionContent = function() { 
      var width = $(window).width(); // the window width 
      var height = $(window).height(); // the window height 
      var containerwidth = $('.container').outerWidth(); // the container div width 
      var containerheight = $('.container').outerHeight(); // the container div height 
      $('.container').css({position:'absolute', 
       left: ($(window).width() - $('.container').outerWidth())/2, 
       top: ($(window).height() - $('.container').outerHeight())/2 }); 
     }; 
     //Call this when the window first loads 
     $(document).ready(positionContent); 
     //Call this whenever the window resizes. 
     $(window).bind('resize', positionContent); 
    }); 
</script> 
+1

你已經得到了你所需要的價值,只是檢查是否winHeight

回答

1

就在窗口尺寸比較容器的尺寸,如果容器比窗口​​高/寬,頂部/左側位置設置爲0:

$('.container').css({ 
    position: 'absolute', 
    left: width > containerwidth ? (width - containerwidth)/2 : 0, 
    top: height > containerheight ? (height - containerheight)/2 : 0 
}); 

順便說一句,你就已經定義widthheightcontainerwidth,並containerheight,所以我不知道爲什麼你沒有在你的代碼重用他們。

+0

謝謝!這是排序:) –