2017-08-02 53 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

您能否爲我們提供一個正在工作的剪貼? –

相關問題