简体   繁体   English

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

[英]full page background image resizable - maintain aspect-ratio

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. 我需要一个简单的jquery解决方案,将背景图像添加到我的页面中,完全填充它,但保持纵横比和垂直和水平居中位置。

there are several plugins out here but I don't want to use any plugin. 这里有几个插件,但我不想使用任何插件。

thanks in advance. 提前致谢。

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 像这样设置你的HTML

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

and your CSS like 和你的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/ 演示 http://jsfiddle.net/gaby/3YLQf/

Or you could use the CSS property : 或者您可以使用CSS属性:

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 您可以使用background-position属性控制图像在视口中的对齐方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM