我需要知道背景图像的实际大小(以像素为单位)。
<style>
body {
background-image: url(background.jpg);
background-size: contain;
}
</style>
当我看jQuery的时候,我尝试了
var img = new Image;
img.src = $('body').css('background-image').replace(/url\(\"|\"\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
但这给我带来的是真实图像的大小,而不是该图像在显示时获得的大小:如果设备有 320px 宽度,bgImgWidth 仍然给我真实图像的 800px。
有人对此有线索吗?
最佳答案
如果能获取图片的宽度和高度,那么就可以根据比例获取显示图片的高度。
var img = new Image();
var $el = $('body');
var containHeight = null;
var containWidth = null;
var containImg = {
w: null,
h: null
};
var bkgImgDims = null;
img.src = $el.css('background-image').replace(/url\(\"|\"\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
var imgProportionalH = Math.abs(bgImgHeight / bgImgWidth);
var imgProportionalW = Math.abs(bgImgWidth / bgImgHeight);
// Get the proportions of the background contain image
function getElProportions() {
var elW = $el.width();
var elH = $el.height();
var elProportionalH = Math.abs(elH / elW);
var elProportionalW = Math.abs(elW / elH);
// Check to see if the image is less than 100% of the element width
if(elProportionalH < imgProportionalH) {
containImg.h = elH;
containImg.w = Math.abs( elH / imgProportionalH );
} else {
containImg.h = Math.abs( elW / imgProportionalW );
containImg.w = elW;
}
return containImg;
}
$(document).ready(function(){
bkgImgDims = getElProportions();
});
$(window).resize(function(){
bkgImgDims = getElProportions();
});
关于jquery - jQuery 中背景图像的实际大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892137/