【问题标题】:Javascript: Adjusting image container height to dynamic image height after image load?Javascript:图像加载后将图像容器高度调整为动态图像高度?
【发布时间】:2010-07-30 13:45:29
【问题描述】:

我通过以下 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 高度后获得这个高度。

我考虑过:

.css("height", THE_IMAGE_HEIGHT)

在 onload 函数中,但我无法找到此图像的高度。调试显示(在onload里面):

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

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

关于如何获得高度的任何想法?

谢谢!

【问题讨论】:

  • 你试过用 .attr("height") 代替 .css("height") 吗?
  • .css('height') 应该直接将属性添加到元素中,与.attr 相同

标签: javascript jquery height image-loading


【解决方案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.
    })
};

试一试,告诉我会发生什么,同时检查控制台日志以查看对象是否是图像元素。

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2018-05-08
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2017-03-10
    • 2014-04-28
    • 1970-01-01
    相关资源
    最近更新 更多