full page background image resizable - maintain as

2019-04-09 10:14发布

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.

thanks in advance.

2条回答
爷的心禁止访问
2楼-- · 2019-04-09 11:07

Or you could use the CSS property :

background-size: cover

This will scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

You can control how your image is aligned within the viewport by using the background-position property

查看更多
Animai°情兽
3楼-- · 2019-04-09 11:10

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');
    });

});

Set your HTML like this

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

and your CSS like

#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/

查看更多
登录 后发表回答