>本文演示瞭如何使用jQuery處理瀏覽器窗口大小,提供了各種技術並解決了常見問題。
>
基本窗口調整大小:
>最簡單的方法使用jQuery的resize
事件:
$(window).resize(function(e) { let width = $(this).width(); let height = $(this).height(); console.log('Window resized to: ' + width + ' by ' + height); });
>
對於需要在調整大小的情況下需要頁面刷新的情況(通常不建議使用),可以使用基於超時的方法進行更廣泛的兼容性(IE8):
setTimeout(function() { $(window).resize(function(e) { clearTimeout(window.RT); window.RT = setTimeout(function() { location.reload(false); // false uses cache }, 300); }); }, 1000);
>
此示例演示了重新定位導航欄:導航欄(
)被輕微延遲重新定位。>
(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);
>
#navbar
對於更順暢的性能,尤其是在調整大小的情況下,拒絕的方法是優越的:
這使用一個辯式函數來限制事件處理的頻率。
原始文本還包括一個常見問題部分,涵蓋了:
(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 });
使用
vs.>手動觸發調整大小事件
刪除調整大小的事件處理程序
.resize()
>處理大小在窗口以外的元素上的大小.on('resize')
以上是jQuery捕獲窗口調整片段的詳細內容。更多資訊請關注PHP中文網其他相關文章!