2

ビューポートが.container divよりも大きい場合にのみ、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/

4

1 に答える 1

1

ウィンドウの寸法とコンテナの寸法をテストする方法は問題ありません。

ただし、イベントを処理すると言うには問題があります。あなたが持っている

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

意味をなさない2回(ちなみに、フィドルでそれを修正しました。おそらくそれが機能する理由です)。

私が理解していることから、あなたはしようとしています: 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);
于 2013-02-22T15:13:03.607 に答える