设定高度; div的背景图像的宽度,事先不知道它们

时间:2013-05-12 01:50:04

标签: javascript jquery html css asynchronous

使用jQuery:

每当有人将背景图像添加到div时,需要事先知道背景图像的宽度和高度。

e.g。

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

我是否可以使用以下代码获取图像的大小:

我已经测试过以下但它不能正常工作,是因为我不能在$ .load函数中使用return语句吗? - 我猜一个return语句需要始终同步吗?

e.g。

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

1 个答案:

答案 0 :(得分: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;