简体   繁体   中英

Calculate the size of a specific portion on a background set with background-size: cover;

I am trying to build an hybrid app and I need to get the size of a specific porition of the background.

  • The background has those properties : background-size: 100% 100%; background: url('back.jpg') no-repeat center center fixed; background-size: 100% 100%; background: url('back.jpg') no-repeat center center fixed;
  • I would like to place a div over that background and set the size of the div to the size of a precise portion of the background.

Here is an image to clarify what I would like to do : Background example with a red rectangle on it

The red rectangle on the backgroud image above is an example of the portion of the image I would like to calculate the size on a responsive screen.

I know how to make the elements follow the right absolute position on the background thanks to this topic Position element over background image , but not how to resize them to the right scale.

Can anyone help ?

I finally managed to fix the problem, which was not as complicated as I thought.

  • The first thing is to know the background width and height
  • The second is to know the size of the element we want on the background (for exemple the red scare)

     // In css : background-size: 100% 100%; var background = {width: 1200, height: 900 }; var redScare = {selector: '.redScare', width: 400, height: 342, x: 50, y: 60}; var xFactor = $( window ).width() / background.width; var yFactor = $( window ).height() / background.height; // New width proportionally to the window size redScare.width = redScare.width * xFactor; // New height proportionally to the window size redScare.height = redScare.height * yFactor; //Setting the new dimensions $(redScare.selector).css('width', redScare.width); $(redScare.selector).css('height', redScare.height); 

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