2010-07-30 65 views
0

我通过以下javascript函数加载图表:Javascript:图像加载后将图像容器高度调整为动态图像高度?

function loadMCorCBGraph(self,surveyID,questionID,varID) { 
    var img = new Image(); 

    img.onload = function() { 
     $(self).parents().parents().siblings(".graph_container") 
     .empty().append(img); 
    }; 

    img.src = 'drawGraph.php?type=surveys_report_MC_or_CB&surveyID=' + surveyID + '&questionID=' + questionID + 
     (varID != null ? '&varID=' + varID : '') + '&companyID=<?php echo $_SESSION['companyID'] ?>'; 
} 

然而,直到它被绘制图形高度是未知的。我想知道是否有一种方法来获得这个高度后,它已经加载并设置容器高度cet高度。在onload功能

.css("height", THE_IMAGE_HEIGHT) 

,但我无法找到该图片的高度:

我想到了把。调试表明(在onload内侧):

$(this).height() = 0 
img.height = ReferenceError: img is not defined 
this.height = 425 

现在最后一个,this.height,显然指的是容器,其被设置与425px的高度。

有关如何获得身高的任何想法?

谢谢!

+0

您是否试过.attr(“height”)而不是.css(“height”)? – 2010-07-30 13:51:06

+0

'.css('height')'应该直接将该属性添加到元素,与'.attr' – RobertPitt 2010-07-30 13:54:28

回答

1
img.onload = function() { 
    $Container = $(self).parents().parents().siblings(".graph_container"); 

    $Container.empty().append(img); 

    this.find('img').each(function(){ 
     //Dynamically check each image 
     if(this.height > 400) 
     { 
      $(this).height(400); 
     } 
     console.log(this); //Should see object with attribs. 
    }) 
}; 

给一个去,告诉我会发生什么,还检查您的控制台日志,看看对象是否是图像元素。

相关问题