jquery - jQuery 中背景图像的实际大小

标签 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。

有人对此有线索吗?

最佳答案

如果能获取图片的宽度和高度,那么就可以根据比例获取显示图片的高度。

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

关于jquery - jQuery 中背景图像的实际大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892137/

相关文章:

javascript - 在弹出的 chrome 扩展中加载 jquery

html - 我怎样才能通过将它们稍微向左移动来在右侧容纳更多链接而不只挤在一行中?

html - Css 虚线下划线的额外点

user-interface - 如何在黑莓中为屏幕创建固定背景?

ios - Firebase iOS 静默推送通知停止在后台传送(一段时间后)

jquery - 我需要获取第一个输入的值,然后添加+1,然后将总和放入文本字​​段

javascript - NPM 安装 jquery 出现错误?定义未定义?

javascript - 如何加载带有关闭检查节点的jstree?

java - 根据excel中选定列中的文本调整行高

CSS - 带有文字的响应式背景图片