整个页面的背景图像调整大小 - 保持纵横比 [英] full page background image resizable - maintain aspect-ratio

查看:866
本文介绍了整个页面的背景图像调整大小 - 保持纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的jQuery解决了背景图片添加到我的网页填充它完全,但保持纵横比和垂直和水平居中的位置。

I need a simple jquery solution to add a background image to my page filling it entirely, but keeping the aspect ratio and vertical and horizontal centered position.

有几个插件在这里,但我不希望使用任何插件。

there are several plugins out here but I don't want to use any plugin.

先谢谢了。

推荐答案

这code会做你想做的。

This code will do what you want..

$(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;
}

演示在 http://jsfiddle.net/gaby/3YLQf/

这篇关于整个页面的背景图像调整大小 - 保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆