背景大小:包含,获得规模后的大小

Bra*_*don 5 html javascript css jquery css3

在CSS中,我将按钮设置为100px x 100px并具有background-size:contains;

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

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

有没有办法做到这一点(我也可以访问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>
Run Code Online (Sandbox Code Playgroud)

Mar*_*k S 6

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

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

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

real_image_widthreal_image_height就像resized_image_widthresized_image_height

首先我们需要得到图像的真实大小:

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

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

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);
Run Code Online (Sandbox Code Playgroud)

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

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

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