2

使用 jQuery:

每当有人将背景图片添加到 div 中时,都需要提前知道背景图片的宽度和高度。

例如

$("#id-of-some-div").css(
{
   backgroundImage: 'url(' + backgroundImageUrl + ')',
   height: 200,
   width: 450,
   position: 'absolute',
   top: 20,
   left: 20
});

我可以简单地通过使用如下代码来获取图像的大小:

我已经测试了以下但它不起作用,是因为我不能在 $.load 函数中使用 return 语句吗?-我猜一个return语句需要总是同步的,对吧?

例如

var bgImageUrl = "/*insert image url*/";

var backgroundImageHeightAndWidth = function(backgroundImageUrl)
{
   var backgroundImageSize = [];
   var backgroundImage = new Image();
   backgroundImage.src = backgroundImageUrl;
   backgroundImage.id = "background-image-id";
   $("#background-image-id").load(function ()
   {
      backgroundImageSize.push($("#background-image-id").height());
      backgroundImageSize.push($("#background-image-id").width());
      return backgroundImageSize;   
   });
};
var backgroundImageHeightAndWidthArray = backgroundImageHeightAndWidth();
var backgroundImageHeight = backgroundImageHeightAndWidthArray[0];
var backgroundImageWidth = backgroundImageHeightAndWidthArray[1];

$("#id-of-some-div").css(
{
   backgroundImage: 'url(' + backgroundImageUrl + ')',
   height: backgroundImageHeight,
   width: backgroundImageWidth,
   position: 'absolute',
   top: 20,
   left: 20
});
4

1 回答 1

4
var bg = "/*insert image url*/";

var bgimg = new Image();
bgimg.onload = function() {
    var elem = document.getElementById('id_of_element');
    elem.style.backgroundImage = 'url(' + bg + ')';
    elem.style.height          = this.height + 'px';
    elem.style.width           = this.width + 'px';
    elem.style.position        = 'absolute',
    elem.style.top             = '20px';
    elem.style.left            = '20px';
});
bgimg.src = bg;
于 2013-05-12T02:00:36.073 回答