简体   繁体   English

jQuery背景始终位于div的中心并保持200px的高度

[英]jquery background always in center of div keeping 200px height

I have a website with a cover image. 我有一个带有封面图片的网站。 The problem is when a user resizes the window, the background does not stay in full height. 问题是当用户调整窗口大小时,背景不会保持全高。

What I want: A Jquery to always put the background image in the center of the div whilst the user resizes the window (keeping the background height and center its width). 我想要的是:一个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');

    });
});

How can I CALC this to put background always in center 100% DIV WIDTH and keeping 200px height? 我如何才能计算出背景始终始终位于100%DIV WIDTH的中心并保持200px的高度?

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

i propose this id #top css: 我建议这个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%;
}

check this out, maybe this is what you need? 检查一下,也许这就是您所需要的?

#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/ http://jsfiddle.net/h64vyr60/3/

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

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