2017-02-28 34 views
2

我做了一個jQuery腳本來檢測3個框的大小。我發現最大的高度(它的工作原理),我設法將最大的尺寸添加到三個盒子。jQuery比較3項並添加最大尺寸

只有它只在頁面加載時才起作用。我把調整爲,但是當我做console.log(maxHeight)時,即使縮小了窗口,該值也總是保持不變。所以,我的箱子不適合。

你能幫我嗎?

謝謝

$(window).on("resize", function() { 

var maxHeight = 0; 


$('.sliderBlog').each(function(){ 
    var thisH = $(this).height(); 
    if (thisH > maxHeight) { maxHeight = thisH; } 
}); 
$('.sliderBlog').height(maxHeight) 
}).resize(); 
+0

這是因爲'maxHeight'是您調用'resize'的匿名函數的局部。 – caisah

+0

將maxHeight移出'$(window)...' – mehulmpt

+0

您應該使用'setTimeout'消除調用resize回調的調用。您不想通過多次呼叫將瀏覽器垃圾郵件。 你可以讓你的代碼更具表現力與功能。儘可能避免全局狀態。 –

回答

1

TL;博士復位高度與.height("auto")比較之前。

您需要用.height("auto")重置高度。

此外,您可能會考慮將此代碼包裝在$(document).ready()中,以便在dom真正準備就緒時運行。 均衡功能可以提取,使其更具功能性和無狀態。 見this codepen;

的JavaScript:

var equalize = function(selector){ 
    var maxHeight = 0; 
    $(selector).each(function(idx,el){ 
    $(el).height("auto"); // resetting height 
    var h = $(el).height(); 
    if (h > maxHeight) { maxHeight = h; } 
    }); 

    $(selector).each(function(idx,el){ 
    $(el).height(maxHeight); 
    }); 
} 

$(document).ready(function(){ 
    equalize(".sliderBlog"); // resize when dom ready 

    // register the resize event listener with debounce 
    $(window).on("resize", function() { 
    setTimeout(function(){ 
     equalize(".sliderBlog"); 
    }, 500); // 500ms debounce before calling the function 
    }); 
}) 

NB:微調防抖時間您的需要。

+0

哇! **非常感謝**,非常感謝您的幫助。它工作得很好,謝謝你的提示! – Jeremy

+0

不用擔心的人。如果解決您的問題,請將其作爲您接受的答案。 –

0

嘗試用這些

$(window).on("resize", function() { 
var maxHeight = 0; 

$('.sliderBlog').each(function(){ 
    var thisH = $(this).height(); 
    if (thisH > maxHeight) { maxHeight = thisH; } 
}); 
$('.sliderBlog').height(maxHeight) 
}); 
0

您似乎在組合兩種不同的調整大小方法。

$(window).on("resize", function(){});是一個DOM事件監聽器。

$(selector).resize(function(){});jQuery method

在任何情況下,你所追求的是接近你所擁有的。下面我修復了你的代碼,並將其包裝在一個去抖動函數中(read here,以瞭解原因)。

var setToMax = debounce(function() { 
    var maxHeight = 0; 
    $('.sliderBlog').each(function(){ 
     var thisH = $(this).height(); 
     if (thisH > maxHeight) { 
      maxHeight = thisH; 
     } 
    }); 
    $('.sliderBlog').height(maxHeight) 
}, 250, true); 

window.addEventListener('resize', setToMax); 

function debounce(func, wait, immediate) { 
    var timeout; 
    return function() { 
     var context = this, args = arguments; 
     var later = function() { 
      timeout = null; 
      if (!immediate) func.apply(context, args); 
     }; 
     var callNow = immediate && !timeout; 
     clearTimeout(timeout); 
     timeout = setTimeout(later, wait); 
     if (callNow) func.apply(context, args); 
    }; 
}; 

你可以在這個JSFiddle看到一個有效的例子。

+0

這並不解決OP的原始問題:當窗口縮小時,高度不會調整大小。 –