Javascript仅在页面刷新后有效

我有一些我在网上找到的代码,使得我网站上的两个div都变得相同。 但是,此代码仅在页面刷新后才有效,我不知道是什么原因造成的。 任何帮助,将不胜感激!

// EQUAL HEIGHTS $.fn.equalHeights = function(px) { $(this).each(function(){ var currentTallest = 0; $(this).children().each(function(i){ if ($(this).height() > currentTallest) { currentTallest = $(this).height(); } }); if (!px && Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified // for ie6, set height since min-height isn't supported if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); } $(this).children().css({'min-height': currentTallest}); }); return this; }; // just in case you need it... $.fn.equalWidths = function(px) { $(this).each(function(){ var currentWidest = 0; $(this).children().each(function(i){ if($(this).width() > currentWidest) { currentWidest = $(this).width(); } }); if(!px && Number.prototype.pxToEm) currentWidest = currentWidest.pxToEm(); //use ems unless px is specified // for ie6, set width since min-width isn't supported if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'width': currentWidest}); } $(this).children().css({'min-width': currentWidest}); }); return this; }; // CALL EQUAL HEIGHTS $(function(){ $('#equalize').equalHeights(); }); 

出现这种情况是因为插件写得不好。 我已经为你修改了它,现在应该可以了。

工作演示

插件脚本:

 // EQUAL HEIGHTS $.fn.equalHeights = function(px) { var currentTallest = 0; $(this).each(function(){ $(this).siblings().each(function(i){ if ($(this).height() > currentTallest) { currentTallest = $(this).height(); } }); }); if (!px && Number.prototype.pxToEm) { currentTallest = currentTallest.pxToEm(); } $(this).siblings().css({'height': currentTallest, 'min-height': currentTallest}); return this; }; 

您可以修改equalWidths插件以用作此插件。

将所有代码放在jquery ready函数中。 内部就绪function代码在DOM准备就绪时执行

 $(document).ready(function(){ //your code });