屏幕尺寸变化时如何移除类?现有resize函数异常排查
Hey Dan, let's break down why your current code isn't behaving as expected and fix it step by step.
Why Your Resize & Click Logic Isn't Working
There are two key issues with your approach:
- Duplicate event bindings: You're wrapping the click event handler inside the
resizeevent'swidth < 992check. Every time the window resizes to under 992px, you add a new click listener. This means multiple listeners fire on a single click, causing thefoot-activeclass to toggle multiple times (making it seem like it's broken). - Lingering event listeners: When the window resizes to over 992px, you don't remove the click listeners you added earlier. So even on large screens, clicking
.foot-titlestill triggers thetoggleClassaction—violating your requirement.
Fixed Solutions
Option 1: Check Window Width Inside the Click Handler
This is the cleaner approach—bind the click event once, and only run the toggle logic if the window is small enough:
// Bind the click event ONCE (not inside resize) $(document).on('click', '.foot-title', function(e) { // Only execute the toggle if we're on a small screen if ($(window).width() < 992) { const parentItem = $(this).parent(); if (parentItem.hasClass('foot-items')) { parentItem.toggleClass('foot-active'); } } // On large screens, this code does nothing—exactly what you want }); // Optional: Clean up state when resizing to large screens $(window).on('resize', function() { if ($(this).width() >= 992) { // Remove the active class from all foot items for a clean large-screen layout $('.foot-items.foot-active').removeClass('foot-active'); } });
Option 2: Dynamically Bind/Unbind the Click Handler
If you prefer to only have the click listener active on small screens, you can add/remove it during resize (just avoid duplicate bindings):
// Define the click handler as a reusable function function toggleFootActive(e) { const parentItem = $(this).parent(); if (parentItem.hasClass('foot-items')) { parentItem.toggleClass('foot-active'); } } // Handle resize events $(window).on('resize', function() { const windowWidth = $(this).width(); if (windowWidth < 992) { // Unbind first to avoid duplicates, then bind the handler $(document).off('click', '.foot-title', toggleFootActive); $(document).on('click', '.foot-title', toggleFootActive); } else { // Remove the click listener entirely for large screens $(document).off('click', '.foot-title', toggleFootActive); // Clean up any active classes to keep layout consistent $('.foot-items.foot-active').removeClass('foot-active'); } }).trigger('resize'); // Trigger resize on page load to set initial state
Both options meet your requirements perfectly:
- Small screens (<992px): Clicking
.foot-titletoggles thefoot-activeclass. - Large screens (>992px): Clicking does nothing, and any leftover
foot-activeclasses are cleared.
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

