jquery - 拉伸背景图像来填充文档而不是窗口?

时间:2010-12-15 18:30:09

标签: javascript jquery image background background-image

我正在使用此插件:https://github.com/srobbin/jquery-backstretch以良好的方式拉伸背景。

所以问题是,如果文档的内容足够长以导致滚动条,那么当您滚动时,图像将保持在同一位置(看起来像静止的背景)。您可以在他的演示中看到它:http://srobbin.com/jquery-plugins/jquery-backstretch/(此页面使用插件。只需滚动并注意背景不会移动)。

我想知道是否有办法将插件更改为不使用窗口高度或其他东西而是使用文档高度?我看了,但无济于事。我知道在内容很长的情况下,这不是一个好主意,但它只在一个页面上完成,根本没有太多内容。真正唯一的问题是浏览器的不动产(不计算铬)高度低于650px。

这是插件代码。我所说的很简短,写得很好: https://github.com/srobbin/jquery-backstretch/raw/master/jquery.backstretch.js

3 个答案:

答案 0 :(得分:0)

我曾遇到同样的问题,这是我的解决方案。

$(window).resize(bg);
function bg() {
    var imgWidth = 1088, 
        imgHeight = 858,
        imgRatio = imgWidth / imgHeight,
        bgWidth = $(document).width(),
        bgHeight = bgWidth / imgRatio;

        $('body').css({backgroundPosition: 'top center'});
        if ($(document).width() < imgWidth && $(document).height() < imgHeight && $(document).height() > bgHeight) {
            $('body').css({backgroundSize: 'auto 100%'});
        } else {
            $('body').css({backgroundSize: '100% auto'});
        }
}
bg();
$('body').css({backgroundRepeat: 'repeat-x'});
$('body').css({backgroundImage: 'url("images/bg-state/bg_static2.png")'});

注意:由于代码使用css3属性background-size而无法在IE上展开,您需要在代码中设置自己的图像宽度和高度。

答案 1 :(得分:0)

使用可滚动内容和固定背景的另一种方法是在图层上使用<iframe>或修复<img>。那么你就不需要依赖jQuery(我认为它有点重)可以在没有它的情况下在浏览器上完成。

<body background="background.png">
    <iframe src="content.html" height="600"/>
</body>

还找到了另一种使用图层的方法:

<img src="background.png" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index:-1;" />
<div style="position: static;z-index: 1; ">
    content
</div>

答案 2 :(得分:-2)

如果不尊重图像比例,我相信您可以将bgHeight设置为$("body").height()

相关问题