您似乎在組合兩種不同的調整大小方法。
$(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看到一個有效的例子。
這是因爲'maxHeight'是您調用'resize'的匿名函數的局部。 – caisah
將maxHeight移出'$(window)...' – mehulmpt
您應該使用'setTimeout'消除調用resize回調的調用。您不想通過多次呼叫將瀏覽器垃圾郵件。 你可以讓你的代碼更具表現力與功能。儘可能避免全局狀態。 –