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

如何将Foundation框架中监听断点变化的jQuery代码转换为纯JavaScript代码?

Convert Foundation Breakpoint Listener from jQuery to Pure JavaScript

Great question! Converting that Foundation breakpoint listener from jQuery to vanilla JS is totally doable—Foundation's custom media query events work seamlessly with native browser APIs. Here's the direct equivalent implementation:

// Pure JS replacement for the jQuery breakpoint listener
window.addEventListener('changed.zf.mediaquery', function(event) {
  // Extract newSize and oldSize from the event's detail property
  const [newSize, oldSize] = event.detail;

  // Reuse your original logic exactly
  if ( 
    (oldSize === "small" && newSize === "large") || 
    (oldSize === "small" && newSize === "xxlarge") || 
    (oldSize === "medium" && newSize === "large") || 
    (oldSize === "medium" && newSize === "xxlarge") 
  ) {
    displayFacets("desktop");
  } else if ( 
    (oldSize === "xxlarge" && newSize === "small") || 
    (oldSize === "large" && newSize === "small") || 
    (oldSize === "large" && newSize === "medium") || 
    (oldSize === "xxlarge" && newSize === "medium") 
  ) {
    displayFacets("mobile");
  }
});

Key Differences from the jQuery Version

  • Event Listening: Replaced jQuery's $(window).on() with native window.addEventListener(), the standard way to listen for events in vanilla JS.
  • Accessing Event Data: jQuery automatically unpacks custom event parameters into the callback function, but native JS stores these values in the event.detail property (as an array here). We use array destructuring to cleanly pull out newSize and oldSize.
  • Logic Reuse: All your original breakpoint condition checks and calls to displayFacets() stay exactly the same—no need to rewrite that business logic.

Bonus: Removing the Listener (If Needed)

If you ever need to stop listening for breakpoint changes, save the callback function to a variable first, then use removeEventListener():

// Store the handler in a variable
const breakpointChangeHandler = function(event) {
  const [newSize, oldSize] = event.detail;
  // Your logic here
};

// Add the listener
window.addEventListener('changed.zf.mediaquery', breakpointChangeHandler);

// Later, remove it when no longer needed
window.removeEventListener('changed.zf.mediaquery', breakpointChangeHandler);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:42:38