您发现的脚本过分复杂的问题。以下为我工作:
$(function(){
// Cache reference to our container
var $container = $("#container");
// A function for updating max-height
function updateMaxHeight() {
$container.css("max-height", $(this).height() - 100);
}
// Call updateMaxHeight when browser resize event fires
$(window).on("resize", updateMaxHeight);
});
一个警告是resize事件调用浏览器时调用了很多;它不仅在浏览器调整大小后才调用。因此,你可以让回调函数被调用数百次 - 这通常是一个坏主意。
解决方案是遏制或消除事件。节流意味着您不会让回调在一段时间内被触发超过x次(可能是每秒5次)。去抖动意味着您在最后一次调整大小事件经过了一定时间后触发回调(等待调整大小事件后500毫秒)。
jQuery目前不支持油门或反弹选项,虽然有插件。 Other popular libraries you may have used do have these features,如下划线:
$(function(){
// Cache reference to our container
var $container = $("#container");
// A function for updating max-height
function updateMaxHeight() {
$container.css("max-height", $(this).height() - 100);
}
// Version of updateMaxHeight that will run no more than once every 200ms
var updateMaxHeightThrottled = _.throttle(updateMaxHeight, 200);
// Call updateMaxHeightThrottled when browser resize event fires
$(window).on("resize", updateMaxHeightThrottled);
});