jquery set height AFTER load

微笑、不失礼 提交于 2019-12-07 01:50:43

问题


I am having a little trouble setting the height of an element that I am loading in dynamically.

I use the jquery load function to load an external (dynamic) page into a div (#cbox) on my current page. Because this sub-page is dynamic, I can't know before-hand what the height of the content is. I want to get the height once content is loaded and set the height of the container div to match so that my color background css goes all the way down. I have tried many variations of 100% height divs in css only, but as soon as I scroll the page, the color scrolls up (100% seems to only set 100% of the browser window height, and b/c the content is dynamically loaded it does not work. My solution is to set the height of the div to the height of the loaded content, but this only works on the SECOND click (because at that point the page is loaded and accessible. What I need to figure out how to do is change the height of the div AFTER the external page has already loaded, but I can't seem to figure it out).

I hope this is understandable to someone, I realize it is a bit convoluted.

here is my onclick code:

jQuery('#cbox').load('externalpage.php');
jQuery('#cbox').height(jQuery('#content').height());

UPDATE: The solutions below work if I want to set the height to that div. But now I find that I only want to set it to that div height IF the content height is TALLER than the window. Otherwise I want it set to 100%. I tried modifying their code slightly to this (onlick event):

jQuery('#cbox').load('<?php the_permalink(); ?>', function() 
   { 
      if (jQuery('#cbox').height() < jQuery('#content').height()) 
      {
         jQuery('#cbox').height(jQuery('#content').height()); 
      } 
      else
      { 
         jQuery('#cbox').height('100%'); 
      }
   });

but it does not work...any ideas?


回答1:


You need to call callback function after content is loaded.

jQuery('#cbox').load('externalpage.php', function() {
   jQuery('#cbox').height(jQuery('#content').height());
});



回答2:


Use the load callback.

jQuery('#cbox').load('externalpage.php', function() {
  jQuery('#cbox').height(jQuery('#content').height());
});


来源:https://stackoverflow.com/questions/3493825/jquery-set-height-after-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!