2017-08-02 91 views
0

我的js脚本在我的页面上设置图片高度时出现问题。第一次加载页面时脚本不起作用

它看起来像这样:

var $bigImages = $('.js-big-image'), 
    $quotes = $('.js-quote'), 
    $quoteImages = $('.js-quote-image'); 

     if (window.innerWidth >= 460) { 
      $bigImages.each(function (index) { 
       var imgHeight = $(this).height()/2; 
       $($quotes[index]).height(imgHeight); 
       $($quoteImages[index]).height($quoteImages[index]/2); 
      }); 
     } 

当我去页第一次,图像获取height:0px;,但是当我重新加载页面的图像会从脚本计算的高度。

用户第一次来时发生这种情况。当我使用Chrome隐身窗口时,问题就存在了,所以只有在第一次重新加载一切正常后才会发生。

非常感谢您的解决方案。

+0

是否正在运行中的$代码(文件)。就绪执行脚本

做到这一点之前() ? –

+2

图像异步加载,因此当您检查它们的大小时,它们尚未加载,大小为0x0。你需要使用每个图像的'load'事件在它的回调中有实际的大小,或者在你的CSS里面定义完全的宽度和高度 – MysterX

+0

@AlanBuchanan是的,我的整个scripts.js被$(document).ready(function (){ //脚本在这里 }); – Robson

回答

2

确保网页完全加载,通过扭曲你的代码到ready功能

$(document).ready(function() { 
    var $bigImages = $('.js-big-image'), 
    $quotes = $('.js-quote'), 
    $quoteImages = $('.js-quote-image'); 

    if (window.innerWidth >= 460) { 
     $bigImages.each(function (index) { 
      var imgHeight = $(this).height()/2; 
      $($quotes[index]).height(imgHeight); 
      $($quoteImages[index]).height($quoteImages[index]/2); 
     }); 
    } 
}); 
+0

我已将我的所有脚本包装在文档中准备就绪:/ – Robson

+0

您能否为我们提供一个正在工作的剪贴? –

相关问题