【问题标题】:Problem getting height from div after ajax requestajax请求后从div获取高度的问题
【发布时间】:2011-07-09 23:06:29
【问题描述】:

我在从一个 ajax 请求填充的 div 获取高度时遇到问题。考虑以下代码

(function($) {
 $.fn.flickr = function(o){
 var s = {
api_key: '',              // [string]    required, see http://www.flickr.com/services/api/misc.api_keys.html
type: null,                 // [string]    allowed values: 'photoset', 'search', default: 'flickr.photos.getRecent'
photoset_id: null,          // [string]    required, for type=='photoset'  
text: null,                     // [string]    for type=='search' free text search
user_id: null,              // [string]    for type=='search' search by user id
group_id: null,             // [string]    for type=='search' search by group id
tags: null,                 // [string]    for type=='search' comma separated list
tag_mode: 'any',            // [string]    for type=='search' allowed values: 'any' (OR), 'all' (AND)
sort: 'date-posted-asc',    // [string]    for type=='search' allowed values: 'date-posted-asc', 'date-posted-desc', 'date-taken-asc', 'date-taken-desc', 'interestingness-desc', 'interestingness-asc', 'relevance'
thumb_size: 's',            // [string]    allowed values: 's' (75x75), 't' (100x?), 'm' (240x?)
size: 'o',                 // [string]    allowed values: 'm' (240x?), 'b' (1024x?), 'o' (original), default: (500x?)
per_page: 100,              // [integer]   allowed values: max of 500
page: 1,                      // [integer]   see paging notes
attr: '',                   // [string]    optional, attributes applied to thumbnail <a> tag
api_url: null,              // [string]    optional, custom url that returns flickr JSON or JSON-P 'photos' or 'photoset'
params: '',                 // [string]    optional, custom arguments, see http://www.flickr.com/services/api/flickr.photos.search.html
api_callback: '?',          // [string]    optional, custom callback in flickr JSON-P response
callback: null              // [function]  optional, callback function applied to entire        <ul>
 };
 if(o) $.extend(s, o);
 return this.each(function(){
 // create unordered list to contain flickr images
     var list = $('<ul>').appendTo(this);
   var url = $.flickr.format(s);
    $.getJSON(url, function(r){
  if (r.stat != "ok"){
    for (i in r){
        $('<li>').text(i+': '+ r[i]).appendTo(list);
    };
  } else {
    if (s.type == 'photoset') r.photos = r.photoset;
    // add hooks to access paging data
    list.append('<input type="hidden" value="'+r.photos.page+'" />');
    list.append('<input type="hidden" value="'+r.photos.pages+'" />');
    list.append('<input type="hidden" value="'+r.photos.perpage+'" />');
    list.append('<input type="hidden" value="'+r.photos.total+'" />');
    for (var i=0; i<r.photos.photo.length; i++){
      var photo = r.photos.photo[i];
      // format thumbnail url
      var t = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_'+photo['secret']+'_'+s.thumb_size+'.jpg';
      //format image url
      var h = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_';
      switch (s.size){
        case 'm':
          h += photo['secret'] + '_m.jpg';
          break;
        case 'b':
          h += photo['secret'] + '_b.jpg';
          break;
        case 'o':
          if (photo['originalsecret'] && photo['originalformat']) {
            h += photo['originalsecret'] + '_o.' + photo['originalformat'];
            break;
          };
        default:
          h += photo['secret'] + '.jpg';
      };
      list.append('<li><a href="'+h+'" '+s.attr+' rel="photographs"><img src="'+t+'" alt="'+photo['title']+'" /></a></li>');
    };
    if (s.callback) s.callback(list);

        $('#photographs ul li a img').fadeTo('fast', 0.7);

        $('#photographs ul li a img').hover(function() {
            $(this).fadeTo('fast', 1);
            },function() {
            $(this).fadeTo('fast', 0.7);
        });

        $("#photographs ul li a").fancybox({
            'hideOnContentClick': false,
            'zoomSpeedIn':      0, 
            'zoomSpeedOut': 0, 
            'overlayShow':      true,
            'overlayColor': '#000',
            'overlayOpacity': 0.9,
            'padding': 0
        });




           var outer = $('#photographs').outerHeight(),
           inner = $('#test').height();


           if(inner>outer){
               alert('Inner exceeded outer');
           }






      };
    });
});
};

最后,我在回调中的所有代码都在处理 ajax 添加的图像本身。我需要计算内部 div 的高度,但我总是得到“0”,因为尚未添加图像。它是怎么做到的?

如果有人可以帮助我,非常感谢!

马蒂斯

【问题讨论】:

    标签: jquery ajax callback height


    【解决方案1】:

    我也遇到过这个问题,我认为不需要做复杂的 javascript hack 的最好方法就是在图像标签中指定图像的宽度和高度。

    【讨论】:

      【解决方案2】:

      正如您所指出的,在加载图像之前,浏览器不会知道图像的宽度和高度(除非手动设置)。

      您可以使用 Image 对象的“onload”事件作为触发器来读取高度和宽度属性。

      关于 div 的高度,尝试通过getComputedStyle 读取它的高度和宽度图像加载之后。同样,您可以使用 onload 事件作为触发器。

      由于您将图像添加为标记而不是对象,因此您可能需要更改方法。例如,您可以跟踪对象中的图像加载:

      var imageLoaded = {}; // 在循环之上定义

      然后,当您迭代您的照片集时,您可以这样做:

      imageLoaded[t] = 假; var imgObject = 新图像; img.onload = 函数 () { imageLoaded[this.src] = true; for(imageLoaded 中的键){ if (!imageLoaded[key]) { 返回; } // 如果我们到达这里,所有图像都会被加载。 // 所以,调用所有需要的函数 //首先加载的图像。 } } img.src = t;

      我忘记了附加子元素的 jQuery 惯用语是什么,但是在将“li”、“a”和“img”组合为标记字符串的地方,可以将其拆分为单独的语句,以便将 img 元素作为对象处理。

      【讨论】:

        【解决方案3】:

        windlow.load 将确保加载所有图像

        $(window).load(function(){
        //initialize after images are loaded
        });
        

        这个链接进一步解释了这个

        http://web.enavu.com/daily-tip/daily-tip-difference-between-document-ready-and-window-load-in-jquery/

        【讨论】:

        • 嗯,如果我在 window.load 函数之间包装该代码,if(outer&gt;inner){ alert('Inner exceeded outer'); } 甚至不再工作(注意'外部>内部',而不是'内部>外部',这使得感觉)。
        • @Mathijs ,是吗,我曾经遇到过类似的问题,当我更改为 window.load 时,它解决了问题,但是让阅读更多的代码并回复你跨度>
        猜你喜欢
        • 2017-09-18
        • 2012-09-27
        • 1970-01-01
        • 2016-08-27
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 2011-05-01
        • 2013-11-26
        相关资源
        最近更新 更多