【问题标题】:jquery background always in center of div keeping 200px heightjquery 背景始终在 div 的中心,保持 200px 高度
【发布时间】:2015-10-09 07:29:57
【问题描述】:

我有一个带有封面图片的网站。 问题是当用户调整窗口大小时,背景不会保持在全高。

我想要的: 一个 Jquery,在用户调整窗口大小时始终将背景图像放在 div 的中心(保持背景高度并使其宽度居中)。

$(document).ready(function() {

    $(window).on('resize', function() {

        //#TOP WIDTH
        var width = $('#top').width();

        //#TOP background IMG width
        var img = new Image;
        img.src = $('#top').css('background-image').replace(/url\(|\)$/ig, "");
        var bgImgWidth = img.width;

        //CALC
        var newImgWidth = (bgImgWidth - width) / 2; //THE PROBLEM

        //NEW BACKGROUND POSITION
        $('#top').css('background-size', newImgWidth + 'px' + ' 200' + 'px');

    });
});

我如何计算这个以将背景始终放在中心 100% DIV WIDTH 并保持 200px 高度?

http://jsfiddle.net/h64vyr60/1/

【问题讨论】:

    标签: jquery


    【解决方案1】:

    看看这个,也许这就是你需要的?

    #top{
    border-bottom:1px solid black;
    width: 100%;
    height: 200px;
    background-image: url("http://www.kohmooksivalairesort.com/include/gallery/slide/13393910371.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;    
    

    }

    http://jsfiddle.net/h64vyr60/3/

    【讨论】:

    • 哦,看起来不错!我会做一些测试,看看它是否有效!
    • 好吧,它可以按我的意愿工作!非常感谢你的朋友!
    【解决方案2】:

    我建议这个 id #top css:

    #top {
      background-image: url("http://www.kohmooksivalairesort.com/include/gallery/slide/13393910371.jpg");
      background-position: 50% 50%;
      background-repeat: no-repeat;
      background-size: auto auto;
      border-bottom: 1px solid black;
      height: 200px;
      width: 100%;
    }
    

    【讨论】:

    • 很好,但我希望图像得到所有#top width
    • 使背景尺寸为:background-size:100% 100%;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多