jQuery中的background-image实际大小

时间:2016-03-09 12:52:49

标签: jquery css background size

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

<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的真实图像。

有人对此有所了解吗?

2 个答案:

答案 0 :(得分:2)

如果您可以获得图像的宽度和高度,则可以根据比例获得显示图像的高度。

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

答案 1 :(得分:0)

插件中的脚本可以提供帮助:来源: 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);