背景大小:包含,缩放后获取大小



在CSS中,我将一个按钮设置为100px x 100px,并具有背景大小:包含;

在javascript中,我将图像应用于我没有高度/宽度(也不是纵横比)的元素。

在javascript的另一个函数中,我需要能够在通过包含函数后获取此按钮的图像/背景的大小。

有没有办法做到这一点(我也可以访问 Jquery)

小样本:

<style>
#imageButton{ 
    width: 100px;
    height: 100px;
    background: url("imageURL"); 
    background-size: contain !important; 
}
</style>
<script>
    var imageElem = $('#imageButton')[0];
    console.log($(imageElem).width());
    //100px but need width of image after scaling
</script>

CSS 属性background-size: contain;将图像缩放到最大,以便高度和宽度都适合内部,当然保持相同的纵横比。

就像@Teemu说的,背景图像是一种伪元素,你实际上无法参考。但是我可以向您展示有关如何获取实际图像大小并计算缩放背景图像大小的解决方法。

它的工作原理类似于比例和比例,其中:

real_image_width之于real_image_height,就像resized_image_width之于resized_image_height

首先,我们需要获取图像的实际大小:

var img = new Image;
img.src = $('#imageButton').css('background-image').replace(/url(|)$/ig, "");
var imgW = img.width;
var imgH = img.height;

然后,比较哪个维度最大并计算比例:

var newW, newH;
if(imgW > imgH){
    newW = $('#imageButton').width(); //100;
    newH = imgH / imgW * newW;
}else{
    newH = $('#imageButton').height(); //100
    newW = imgW / imgH * newH;      
}
console.log(newW+':'+newH);

如果图像尚未加载或缓存,它将返回大小 0,解决此问题的一个好方法是在使用 .load() 函数加载图像时获取大小。

浏览器在亚像素渲染方面也有所不同,我认为您需要四舍五入到最接近的 .5 小数才能获得最安全的确切值 (43.7832 => 43.5)。使用:(Math.round(value * 2) / 2).toFixed(1)

就是这样!这是示例小提琴。

最新更新