![](/img/trans.png)
[英]Getting the height of a background image resized using “background-size: contain”
[英]Get XY coords & Height/Width of div background image, when using background-size:contain
我正在设计一个网页,其中包含主页背景图片的照片。 图像必须覆盖尽可能多的可用窗口大小,同时保持正确的宽高比。
为此,我有一个带有以下CSS的“容器”div:
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%;
}
这是完美的。
但是,我现在需要在图像上的特定位置放置其他dom元素,这些元素也会缩放到与背景图像相同的位置。
我最初认为使用JQuery并阅读“background-image-x”,“background-image-y”,“background-image-x”,“background-position-x”和“background-position-y”CSS属性可能会为我提供定位其他元素所需的信息。
但是,这些并不返回所需的信息(例如,image-x和image-y都返回“50%”)。
是否有一些很好的和简单的(ish)方法来实现我需要的...或者我将不得不求助于使用Javascript和数学手动设置背景图像的位置和大小(从而给我我需要的答案)?
我讨厌数学。 请不要让我使用它:)
你可以用一些非常简单的比较比例来解决这个问题,图像宽度与图像高度相比,容器宽度与容器高度相比。 确定图像是水平还是垂直缩放。
img_ratio = img_width / img_height;
container_ratio = $(elm).width() / $(elm).height();
接下来,您可以非常简单地计算偏移量,因为您可以计算出图像缩放的百分比。 并将其应用于相反的消息,并将其与容器进行比较。
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];
}
我把它包含在一个示例小提琴中: http : //jsfiddle.net/y2LE4/
我希望能帮到你。
试试:
$(document).ready(function(){
var something = background.offset();
}
要么
$(document).ready(function(){
var something = $('.background').outerWidth(true);
}
或者只是宽度功能: http : //api.jquery.com/width/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.