jQuery:检测浏览器resize

我从snipplr使用这个脚本,我如何设置它,使容器div比newWindowHeight高度小100px,如-100或其他东西。

 $(document).ready(function(){ //If the User resizes the window, adjust the #container height $(window).bind("resize", resizeWindow); function resizeWindow( e ) { var newWindowHeight = $(window).height(); $("#container").css("max-height", newWindowHeight ); } });  

你发现的脚本过于复杂了这个问题。 以下对我有用:

 $(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事件; 它不仅仅是在浏览器resize后调用的。 因此,您可以将回调函数调用数百次 – 这通常是一个坏主意。

解决方案是扼杀或去除事件。 限制意味着你不会让回调在一段时间内被触发超过x次(可能是每秒5次)。 去抖意味着您在从上一次resize事件(等待resize事件后500毫秒)过去一段时间后触发回调。

虽然有插件,jQuery目前不支持限制或去抖选项。 您可能使用过的其他常用库也具有这些function ,例如下划线:

 $(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); }); 

我刚刚看到名为“onResize”的HTML事件属于特别标记。我认为它将具有更多的性能,然后使用这种用法进行java检测。

  

我希望它会帮助你们..