全屏背景图片可调整大小 - 保持宽高比

4
我需要一个简单的jQuery解决方案来添加背景图像,使其填满整个页面,但保持纵横比和垂直水平居中位置。虽然有几个插件可以使用,但我不想使用任何插件。谢谢提前。

1
你知道如果一个页面很长,图片会变得难以辨认,因为你保持了宽高比,从而使图片变得非常宽。 - Jason Kaczmarsky
我的页面无法向下或向右滚动,它固定在浏览器窗口中。所有内容都在窗口限制内。 - Emilio Yero
2个回答

8
这段代码将实现你所需的功能。
$(function(){

    var stretcher = $('#background-container > img'),
        element = stretcher[0],
        currentSize = { width: 0, height: 0 },
        $document = $(document);

    $(window).resize(function () {
        var w = $document.width();
        var h = $document.height();

        if (currentSize.width != w || currentSize.height != h) {
            stretcher.width(w).height('auto');
            if (h > element.height) {
                stretcher.width('auto').height(h);
            }
            currentSize.width = w;
            currentSize.height = element.width;
        }
    })

    $(window).load(function () {
        $(this).trigger('resize');
    });

});

请按照以下方式设置您的 HTML

<div id="page">
    Your page contents here..
</div>
<div id="background-container">
      <img src="path/to/image" />
</div>

您的CSS也要这样:

#background-container{
    position:absolute;
    z-index:1;
    top:0;
    left:0;
    width:100%;
    height:100%;
    overflow:hidden;
}

#page{
    position:relative;
    z-index:5;
}

Demo at http://jsfiddle.net/gaby/3YLQf/


@ Gaby,正在工作,谢谢。但是图片从某个点开始不会再缩小了,比如 800x600 大小的图片就不会再调整大小了。 - Emilio Yero
@Emilio,如果你想让它在窗口比内容小的情况下也能缩放,那么把 $document = $(document); 改成 $document = $(window); - Gabriele Petrioli
现在我需要将这个应用到一个使用ajax的图片上,很抱歉打扰你,提前谢谢。 - Emilio Yero
你是说?你从脚本中动态加载图片吗?如果是的话,你需要取消绑定重设大小处理程序,并在图片加载后(在图片的加载处理程序上)重新运行整个脚本。 - Gabriele Petrioli

4

或者你可以使用CSS属性:

background-size: cover

这将按比例缩放图像,以使其完全覆盖背景定位区域的宽度和高度,并保留其固有的长宽比(如果有)。

您可以使用background-position属性控制图像在视口中的对齐方式。


还有一种方法可以让图像保持居中吗? - Jonathan
2
background-position: 50% 50% 就可以了。 - Ahmad Alfy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接