ホームページ >ウェブフロントエンド >jsチュートリアル >jQueryキャプチャウィンドウのサイズ変更スニペット
この記事では、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>これにより、各サイズ変更のコンソールに新しいウィンドウの寸法が記録されます。
sezize(hacky solution)で更新されるページ:
サイズのページを更新する必要がある状況(一般的には推奨されません)の場合、タイムアウトベースのアプローチをより広範な互換性に使用できます(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>よくある質問:
元のテキストには、次のようなトピックをカバーするFAQセクションも含まれています。
vs.
.resize()
サイズのイベントを手動でトリガーします.on('resize')
以上がjQueryキャプチャウィンドウのサイズ変更スニペットの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。