You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用resize事件监听document宽度而非window宽度?

Fixing Resize Logic to Use Document Width Instead of Window Width

Got it, let's get this sorted for you! Your current code is on the right track, but we need two key adjustments: switching to check the document width instead of window width, and fixing a small jQuery syntax mistake in how you're selecting elements.

What's Off with the Original Code?

  • You’re using $(document).getElementsByClass() which isn’t a valid jQuery method—jQuery uses the $(".class-name") syntax for targeting elements by class.
  • The width check is tied to window instead of document, which is what you specifically requested.

Corrected Working Code

// We still listen for the window resize event (resize is a window-level event)
$(window).resize(function() {
  // Grab the full document width instead of viewport width
  const docWidth = $(document).width();
  
  if (docWidth < 960) {
    $(".razdel5").removeClass("d-none");
    $(".fade-i").addClass("d-none");
  } else {
    $(".razdel5").addClass("d-none");
    $(".fade-i").removeClass("d-none");
  }
});

Key Changes Breakdown

  • Switched to document width: Replaced $(window).width() with $(document).width() to base our breakpoint logic on the full width of the document, not just the visible viewport.
  • Fixed jQuery selectors: Swapped the invalid getElementsByClass calls with proper jQuery class selectors ($(".razdel5") and $(".fade-i")), which is the standard way to target elements by class in jQuery.

Bonus: Add Debouncing for Better Performance

Resize events fire extremely frequently as the user drags the window edge. Adding a debounce ensures your code only runs after the user stops resizing for a short time, which reduces unnecessary computations and improves performance:

// Simple debounce function to limit execution frequency
function debounce(func, delay = 100) {
  let timeoutId;
  return function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, arguments), delay);
  };
}

// Wrap our resize logic in the debounce to optimize
$(window).resize(debounce(function() {
  const docWidth = $(document).width();
  
  if (docWidth < 960) {
    $(".razdel5").removeClass("d-none");
    $(".fade-i").addClass("d-none");
  } else {
    $(".razdel5").addClass("d-none");
    $(".fade-i").removeClass("d-none");
  }
}));

This way, your code won’t run hundreds of times during a single resize action—only once the user has finished adjusting the window size.

内容的提问来源于stack exchange,提问作者mex111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:46:44