2013-02-22 16 views
2

我想在jquery中創建以下內容,我正在嘗試將格式應用於div,只有當視口大於.container DIV。我寫了以下內容,但我不確定是否正確完成了,因爲我的Jquery並不好。應用以下格式,除非視口小於容器div - 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(); // 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 

    if ((width >= containerwidth) && (height>=containerheight)){ //if the width and height of the window is bigger than the container run this function 
    $(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(); 
    }); 
    } 
    }); 


    EDIT >> 

............................................ .........

我已經在這裏創建了一個js小提琴,現在似乎在工作。

http://jsfiddle.net/QgyPN/

回答

1

您測試窗口尺寸和容器尺寸的方式是罰款。

然而,對待你的事件有說有問題。你有

$(document).ready(function() { 
    //... 
}); 

兩次這是沒有意義的(你在你的提琴的方式,這可能是爲什麼它的工作原理固定的)。

據我所知,你試圖: 1.當頁面加載時,如果窗口足夠大,應用某些CSS。 2.在後續頁面調整大小,做同樣的事情

所以我建議你隔離你的代碼,應用CSS。這樣,你就可以多次使用它:

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 

    if ((width >= containerwidth) && (height>=containerheight)){ 
     $('.container').css({position:'absolute', 
          left: ($(window).width() - $('.container').outerWidth())/2, 
          top: ($(window).height() - $('.container').outerHeight())/2 }); 
    } 
}; 

然後,當你需要使用的功能:

//Call it when the window first loads 
$(document).ready(positionContent); 

//Call it whenever the window resizes. 
$(window).bind('resize', positionContent); 
+0

感謝您的幫助,我現在有兩個答案,像你後,我說:刪除了第二個文檔準備好了,我不知道那是怎麼回事,認爲這是我複製代碼。我會用你的比我小很多,寫得好多了!謝謝 ! – 2013-02-22 15:18:01