简体   繁体   中英

Get XY coords & Height/Width of div background image, when using background-size:contain

I'm designing a web page that has a photo for a background image of the main page. The image must cover as much of the available window size as possible, whilst maintaining the correct aspect ratio.

To that end, I have a "container" div with the following CSS:

div.background {
    background-image: url('/Content/Images/Home/main-bg.png');
    background-repeat:no-repeat;
    background-size:contain;
    background-position:center;    
    float:left;
    width:100%;
}

which is working perfectly.

However, I now need to position additional dom elements at specific places on the image, which are also scaled to the same as background image.

I initially thought that using JQuery and reading the "background-image-x","background-image-y", "background-image-x", "background-position-x", and "background-position-y" CSS properties might give me the information I need to position the additional elements.

However, these are not returning the needed information (for example, image-x and image-y both return "50%").

Is there some nice and simple(ish) way to achieve what I need... or am I going to have to resort to using Javascript and math to manually set the position and size of the background image (thus giving me the answers I need)?

I hate math. Please don't make me use it :)

You could work this out with some quite simple comparative ratios, of the image width vs image height compared to container width vs container height. To work out whether the image will be scaled horizontally or vertically.

img_ratio = img_width / img_height;
container_ratio = $(elm).width() / $(elm).height();

Following that you can work out the offset quite simply as you can work out by what percentage the image has been scaled. And apply that to the opposite mesasurement, and compare it to the container.

if(container_ratio > img_ratio){
    //centered x height 100%
        var scale_percent = $(elm).height() / img_height;
        var scaled_width = img_width * scale_percent;
        var x_offset = ($(elm).width() - scaled_width) / 2;
        offset = [x_offset, 0];
}else{
    //centered y width 100%
        var scale_percent = $(elm).width() / img_width;
        var scaled_height = img_height * scale_percent;
        var y_offset = ($(elm).height() - scaled_height) / 2;
        offset = [0, y_offset];
}

I've wrapped this up in an example fiddle at: http://jsfiddle.net/y2LE4/

I hope to help.

Try with:

$(document).ready(function(){

var something = background.offset();

 }

or

$(document).ready(function(){
      var something = $('.background').outerWidth(true);
}

Or just the width feature: http://api.jquery.com/width/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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