使用 background-size:cover
用 400x200 的背景图像覆盖浏览器的视口(viewport):
html, body {height:100%;}
body {background:url("http://lorempixel.com/g/400/200/") center no-repeat; background-size:cover;}
我想通过 javascript 检索应用于图片的计算 background-size
值,例如 1536px 768px
现场演示:http://s.codepen.io/abernier/fullpage/rHkEv
注意:我只是想阅读,而不是计算它(因为浏览器在某种程度上已经有了)
最佳答案
我知道我来晚了,但我已经使用下面的代码解决了这个问题。
var backgroundImage = new Image();
backgroundImage.src = $('my_div_id').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
backgroundImage.onload = function() {
var width = this.width;
var height = this.height;
var object = $('#my_div_id');
/* Step 1 - Get the ratio of the div + the image */
var imageRatio = width/height;
var coverRatio = object.outerWidth()/object.outerHeight();
/* Step 2 - Work out which ratio is greater */
if (imageRatio >= coverRatio) {
/* The Height is our constant */
var coverHeight = object.outerHeight();
var scale = (coverHeight / height);
var coverWidth = width * scale;
} else {
/* The Width is our constant */
var coverWidth = object.outerWidth();
var scale = (coverWidth / width);
var coverHeight = height * scale;
}
var cover = coverWidth + 'px ' + coverHeight + 'px';
alert('scale: ' + scale + ', width: ' + coverWidth + ', height: ' + coverHeight + ', cover property: ' + cover);
};
可以在此处找到详细的演练 http://www.gene.co.uk/get-computed-dimensions-background-image-background-size-cover/
关于javascript - 从背景大小 :cover/contain 中检索计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21216408/