【问题标题】:background-image actual size in jQueryjQuery中的背景图像实际大小
【发布时间】:2016-03-09 12:52:49
【问题描述】:

我需要知道背景图像的实际大小(以像素为单位)。

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

有人知道吗?

【问题讨论】:

  • 然后尝试抓取元素(body)的大小?
  • 问题是如果我需要知道图像大小,而不是 尺寸。例如,主体可以具有屏幕的大小,但图像可以具有其他大小。
  • 因此,background-size:contain 属性保留了图像的比例。如果您将该比率输入到计算中,您也许可以算出这一点。获取body的宽度并根据比例计算高度

标签: jquery css background size


【解决方案1】:

如果你能得到图片的宽高,那么你可以根据比例得到显示的图片的高度。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多