>本文演示了如何使用jQuery处理浏览器窗口大小,提供了各种技术并解决了常见问题。
>
基本窗口调整大小:
>最简单的方法使用jQuery的resize
事件:
<code class="language-javascript">$(window).resize(function(e) { let width = $(this).width(); let height = $(this).height(); console.log('Window resized to: ' + width + ' by ' + height); });</code>这将新的窗口尺寸记录到每个大小的控制台。 > page Reversh on Resize(hacky解决方案):
>
对于需要在调整大小的情况下需要页面刷新的情况(通常不建议使用),可以使用基于超时的方法进行更广泛的兼容性(IE8):
<code class="language-javascript">setTimeout(function() { $(window).resize(function(e) { clearTimeout(window.RT); window.RT = setTimeout(function() { location.reload(false); // false uses cache }, 300); }); }, 1000);</code>
>
此示例演示了重新定位导航栏:导航栏(
)被轻微延迟重新定位。>
<code class="language-javascript">(function($, W) { function repositionNav() { let newTop = W.innerHeight - 300; newTop = Math.min(newTop, 550); // Max top position $('#navbar').css('top', newTop); } repositionNav(); $(W).resize(function(e) { clearTimeout(W.RT); W.RT = setTimeout(repositionNav, 300); }); })(jQuery, window);</code>拒绝的调整大小事件以进行性能:
>
#navbar
对于更顺畅的性能,尤其是在调整大小的情况下,拒绝的方法是优越的:
这使用一个辩式函数来限制事件处理的频率。
原始文本还包括一个常见问题部分,涵盖了:
<code class="language-javascript">(function($, sr) { let debounce = function(func, threshold, execAsap) { let timeout; return function() { let obj = this, args = arguments; function delayed() { if (!execAsap) func.apply(obj, args); timeout = null; } clearTimeout(timeout); timeout = setTimeout(delayed, threshold || 100); }; }; jQuery.fn[sr] = function(fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); }; })(jQuery, 'smartresize'); $(window).smartresize(function() { // Your efficient resize code here });</code>
使用
vs.>手动触发调整大小事件
删除调整大小的事件处理程序
.resize()
>处理大小在窗口以外的元素上的大小.on('resize')
以上是jQuery捕获窗口调整片段的详细内容。更多信息请关注PHP中文网其他相关文章!