2016-09-28 68 views
0

我已经使用这个JavaScript代码片段创建了一堆divs与之前等同的高度,以前从未有过这个问题,但由于某种原因,代码没有运行,直到我刷新页面。下面是一个简单的实例:Javascript没有运行,直到刷新

<div class="container"> 
    <div class="row text-center"> 

    <%= link_to "http://www.manlyartofbbq.com" do %> 
     <div class="col-sm-6 col-md-4"> 
     <div class="site-preview-box"> 
      <h2>WIP: Manly Art of BBQ</h2> 
      <h4>Branding, Logo Design, UI/UX Design, Web Development</h4> 
      <%= image_tag 'portfolio_mab.png', class: "portfolio-image" %> 
      <p><a href="www.manlyartofbbq.com">The Manly Art of BBQ</a> is a humorous website that gives information on a variety of "manly" topics.</p> 
      <p><strong>This site has a vast array of user-submitted content sorted in a Reddit-like fashion, as well as a few online "tools" that were a lot of fun to develop.</strong></p> 
     </div> <!-- site preview box --> 
     </div> <!-- column box --> 
    <% end %> 

    <%= link_to "http://www.ocoutreach.com" do %> 
     <div class="col-sm-6 col-md-4"> 
     <div class="site-preview-box"> 
      <h2>WIP: OC Outreach</h2> 
      <h4>Branding, Logo Design, UI/UX Design, Web Development</h4> 
      <%= image_tag 'portfolio_oco.png', class: "portfolio-image" %> 
      <p><a href="www.ocoutreach.com">OC Outreach</a> is a non-profit community organization that operates in the Orange County area.</p> 
      <p><strong>This was a fairly simple site functionality-wise, but it was cool to design every aspect of a site (logos, design, etc.) from the ground up.</strong></p> 
     </div> <!-- site preview box --> 
     </div> <!-- column box --> 
    <% end %> 


    </div> <!-- row --> 

</div> <!-- page container --> 


<script> 
    $(document).ready(function() { 
     var heights = $(".site-preview-box").map(function() { 
      return $(this).height(); 
     }).get(), 
     maxHeight = Math.max.apply(null, heights); 
     $(".site-preview-box").height(maxHeight); 
     window.onresize = function(){ location.reload(); } 
    }); 
</script> 

取而代之的同样高的divs,我结束了这一点:

Problem Example Image

然后,当我打刷新(有时需要多次刷新),它纠正这个:

Problem Fixed Image

如何得到这个我以前工作的任何想法刷新页面?

补充信息 这不是由this question的答案解决。我试着用load代替ready,并且它为此目的呈现javascript无效。

+3

'window.onresize = function(){location.reload(); } - 好 - 这有点可怕 - 它也可能无法在第一次加载时工作,因为在加载图像之前高度获得它们的值。我只是猜测 – tymeJV

+0

[嵌套图像加载后找到元素高度的一致方式]可能的重复(http://stackoverflow.com/questions/13489883/consistent-way-of-finding-element-height-after- nested-image-has-loaded) – Serlite

+0

(如果有人可以找到更好的选择,请这样做) – Serlite

回答

0

您可以为图像指定css的宽度和高度。所以盒子会随时看起来像你想的那样。 就你而言,浏览器在第一时间缓存图像,然后由于从浏览器缓存中读取图像而第二次显示图像。

+0

图像都有80%的宽度,所以他们调整屏幕.... – Liz

1

让您的divs在所有图像完成加载后出现。 div在重新加载时是正确的大小,因为那时所有的图像都被浏览器缓存,并且JavaScript可以选择合适的大小。

jQuery中改变你的ready此:

$(window).on("load", function() { // weave your magic here. });

应该修复它。如果不。

像这样的东西应该有助于作为一个粗略的例子。

var img = new Image(); 
img.onload = function() { alert("Height: " + this.height); } 
img.src = "http://path/to/image.jpg" 
+0

第一个没有办法。它删除了刷新问题,但从来没有调整divs ....第二... – Liz