-2

我正在使用此链接中的代码http://css-tricks.com/perfect-full-page-background-image/

    <script>
        $(function() {   

              var theWindow        = $(window),
                  $bg              = $("#bg"),
                  aspectRatio      = $bg.width() / $bg.height();

              function resizeBg() {

                if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
                    $bg
                      .removeClass()
                      .addClass('bgheight');

                } else {
                    $bg
                      .removeClass()
                      .addClass('bgwidth');
                }

                $bg.style.marginTop = (-theWindow.height() / 2) + 'px';
                $bg.style.marginLeft = (-theWindow.width() / 2) + 'px';

              }

              theWindow.resize(function() {
                resizeBg();
              }).trigger("resize");

            });
    </script>
    <style>
    #bg { position: fixed; top: 0; left: 0; z-index:-2;}
    .bgwidth { width: 100%; }
    .bgheight { height: 100%; }
    </style>
    <body>
       <div id="caseStudies">
            <img src="images/caseStudy01.jpg" alt="Case Study 1" id="bg">
        </div>
</body>

但我想将背景图像居中。我已经尝试使用以下代码:

$bg.style.marginTop = (-theWindow.height() / 2) + 'px';
$bg.style.marginLeft = (-theWindow.width() / 2) + 'px';

这是行不通的。我是否引用了正确的值?

4

1 回答 1

0

我认为你应该试试这个:

    $bg.style.marginTop = ($bg.height()/2-theWindow.height() / 2) + 'px';
    $bg.style.marginLeft = ($bg.width()/2-theWindow.width() / 2) + 'px';
于 2013-01-30T10:51:32.340 回答