if语句-除非视口小于容器div-Jquery,否则应用以下格式



我正试图在Jquery中创建以下内容,我试图做的是仅当视口比.containerdiv大时才对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 fiddle,它现在似乎正在工作。

http://jsfiddle.net/QgyPN/

测试窗口维度和容器维度的方法很好。

然而,你对待事件的发言权却存在问题。你有

$(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);

最新更新