背景图像实际大小 jQuery

background-image actual size in jQuery

我需要知道背景图片的实际像素大小。

<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();
});

JSBin Example

插件中的脚本可以提供帮助:来源: https://gist.github.com/schmidsi/1276118

我把它放在 JSFiddle 中并添加到其中,这样您就可以看到正文并将其与背景图片进行比较。

var url = $('body').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
var bodyHeight = $('body').height();
var bodyWidth = $('body').width();

bgImg.hide();
bgImg.bind('load', function()
{
    var imgHeight = $(this).height();
    var imgWidth = $(this).width();

    alert("Body height: " + bodyHeight + "px, Body width: " + bodyWidth + "px");
    alert("Image height: " + imgHeight + "px, Image width: " + imgWidth + "px");
});
$('body').append(bgImg);
bgImg.attr('src', url);