2017-06-15 105 views
1

我有我寫了如下主要功能:高度相等不能正常工作。js文件

function getListHeight() { 
 

 
    $(".tur-list .col-lg-5 figure img").each(function() { 
 
     var getTurHeight = $(this).parents(".tur-list").find(".col-lg-7").outerHeight(); 
 
     var getLeftHeight = $(this).parents("tur-list").find(".col-lg-5 figure img").outerHeight(); 
 
     if (getTurHeight > getLeftHeight) { 
 
      $(this).outerHeight(getTurHeight); 
 
     } 
 
    }); 
 
}

使等於我的專欄和它的作品,因爲我想所以沒有什麼到這裏。我的問題是這樣的代碼不工作在我的js文件,但如果我複製並粘貼安慰我的代碼工作,所以如果你嘗試,你會看到

Please click to my real demo

和複製getListHeight();並粘貼在控制檯上你會看到我的列將是平等的我的問題是爲什麼我的代碼在.js文件中無法正常工作?我需要做什麼來處理我的代碼?

和我的getListHeight()函數與$(window).resize一起使用時調整窗口或單擊事件,但我的函數不能在document.ready中工作。

+0

在窗口加載時調用它,而不是(或除此之外)文檔準備好 –

+2

同步問題?這可能是因爲當document.ready()事件觸發時,還有尚未加載的圖像?你描述了在滿載之後函數對resize()事件起作用的症狀表明document.ready()還沒有得到所有的元素。 Document.ready()不會等待圖像被加載,我認爲。 –

+0

@Mohit Bhardwaj比它最近加載,所以這不是我想要的.. @ Vanquished Wombat,所以我必須做什麼,我將如何改變我的代碼? –

回答

2

它不工作,因爲圖像尚未加載,圖像標籤在那裏,但尺寸尚未設置,因爲圖像仍在加載。

我會的代碼更改爲以下:

function matchSize() { 
    var getTurHeight = $(this).parents(".tur-list").find(".col-lg-7").outerHeight(); 
    var getLeftHeight = $(this).parents("tur-list").find(".col-lg-5 figure img").outerHeight(); 
    if (getTurHeight > getLeftHeight) { 
    $(this).outerHeight(getTurHeight); 
    } 
} 
function onResize() { 
    $(".tur-list .col-lg-5 figure img").each(matchSize); 
} 
function getListHeight() { 
    $(".tur-list .col-lg-5 figure img").load(matchSize); 
} 

$(document).ready(function(){ 
    getListHeight(); 
    $(document).on('resize', onResize) 
    onResize() 
}); 

這將在調整大小工作,在新加載的圖像,並在(可能緩存圖像)的JavaScript踢前在過去加載的圖像。

這裏是對codepen叉鏈接:https://codepen.io/Bamieh/pen/gRLPqm

附:我建議您不要依賴col-*類作爲選擇器,因爲只要您更改樣式,代碼就會很容易中斷,使用data-*屬性進行選擇是我認爲的方式。

+0

謝謝我在codepen上試過,但沒有工作,例如: https://codepen.io/cowardguy/pen/qjqbMW –

+0

謝謝你在codepen!我會在第二個更新答案 – Bamieh

+0

@ani_css現在檢查答案 – Bamieh