窗口resize时通过对象key更新变量:纯JS实现滑块breakpoints匹配
完整实现代码
首先你原有配置中breakpoints两个配置项之间缺少逗号,先修正语法问题后完整实现如下:
let config = { perItem: 4, breakpoints: { 992: { perItem: 3 }, 768: { perItem: 2 } } } let perItem = config.perItem // 防抖函数,避免resize事件高频触发计算 function debounce(func, delay = 150) { let timer = null return function(...args) { clearTimeout(timer) timer = setTimeout(() => func.apply(this, args), delay) } } // 更新perItem逻辑(默认max-width匹配:窗口宽度≤断点值时生效) function updatePerItem() { const currentWidth = window.innerWidth // 断点降序排序,优先匹配最大的符合条件的阈值 const breakpoints = Object.keys(config.breakpoints) .map(Number) .sort((a, b) => b - a) let currentPerItem = config.perItem for (const breakpoint of breakpoints) { if (currentWidth <= breakpoint) { currentPerItem = config.breakpoints[breakpoint].perItem break } } perItem = currentPerItem // 此处可添加滑块组件重新渲染的逻辑 console.log('当前perItem值:', perItem) } // 页面加载时初始化一次 updatePerItem() // 监听窗口resize事件,用防抖包装优化性能 window.addEventListener('resize', debounce(updatePerItem))
可选匹配逻辑
如果你需要和swiper官方保持一致的min-width匹配规则(窗口宽度≥断点值时生效),只需修改updatePerItem函数如下即可:
function updatePerItem() { const currentWidth = window.innerWidth // 断点升序排序,优先匹配最小的符合条件的阈值 const breakpoints = Object.keys(config.breakpoints) .map(Number) .sort((a, b) => a - b) let currentPerItem = config.perItem for (const breakpoint of breakpoints) { if (currentWidth >= breakpoint) { currentPerItem = config.breakpoints[breakpoint].perItem } } perItem = currentPerItem // 此处可添加滑块组件重新渲染的逻辑 console.log('当前perItem值:', perItem) }
内容的提问来源于stack exchange,提问作者Mohammad Sayem
相关产品推荐
相关产品推荐

