以javascript为中心整页背景图片

时间:2013-01-30 10:44:29

标签: javascript jquery

我正在使用此链接中的代码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';

哪个不行。我是否引用了正确的值?

1 个答案:

答案 0 :(得分:0)

我认为你应该尝试这个:

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