ajax请求后从div获取高度的问题

发布于 2024-10-20 17:08:59 字数 4626 浏览 2 评论 0原文

我在获取由 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”,因为图像尚未添加。它是如何做到这一点的?

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

马蒂斯

I'm having a problem getting height from a div which is being filled by an ajax request. Consider following code

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






      };
    });
});
};

At the very end, all my code in the callback is working on the ajax added images itself. I need to calculate the height of the inner div but i always get '0' because the images haven't been added yet. How do it do that?

Thank you very much if anyone can help me!

Mathijs

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北城孤痞 2024-10-27 17:08:59

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 /

windlow.load will ensure all the images are loaded

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

this link explains even furthur on this

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

凌乱心跳 2024-10-27 17:08:59

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

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

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

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

var imageLoaded = {}; // Define above the loop 

然后,当您迭代照片集合时,您可以执行以下操作:

imageLoaded[t] = false;
var imgObject = new Image;
img.onload = function () {
  imageLoaded[this.src] = true;
  for (key in imageLoaded) {
    if (!imageLoaded[key]) {
      return;
    }
    // All images are loaded if we get here.
    // So, call the function that requires all
    // images to be loaded first.
  }
}
img.src = t;

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

As you point out, the width and height of the images will not be known to the browser until they are loaded (unless they are set manually).

You can use the 'onload' event of an Image object as a trigger to read the height and width properties.

Regarding the height of the div, try reading its height and width via getComputedStyle after the images are loaded. Again, you can use the onload event as a trigger.

Because you are adding the images as markup rather than objects, you may need to change your approach. For example, you could track image loads in an object:

var imageLoaded = {}; // Define above the loop 

Then as you are iterating your photo collection you could do this:

imageLoaded[t] = false;
var imgObject = new Image;
img.onload = function () {
  imageLoaded[this.src] = true;
  for (key in imageLoaded) {
    if (!imageLoaded[key]) {
      return;
    }
    // All images are loaded if we get here.
    // So, call the function that requires all
    // images to be loaded first.
  }
}
img.src = t;

I forget what the jQuery idiom is for appending a child element, but where you are assembling the 'li', 'a' and 'img' as a string of markup, you could split it up into separate statements in order to handle the img element as an object.

初见你 2024-10-27 17:08:59

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

I've encountered this problem as well, I think the best way without needing to do complicated javascript hacks is to just specify the image widths and heights in the image tags.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文