如何根据窗口尺寸动态调整flexiblePagination的itemsPerPage每页条数
问题原因及修复代码
存在的问题
detect函数内的count是局部变量,且没有设置返回值,外部无法获取计算后的数值- 分页组件初始化时传入的
count未完成赋值,属于未定义变量,配置直接失效 - 窗口 resize 事件仅重新计算了条目数,没有更新分页组件的配置并重新渲染,修改不会生效
- 代码存在语法错误:
detect(width)与后续绑定resize事件的代码之间缺少分隔符,会触发运行报错
修复后的完整代码
// 调整detect函数,返回计算得到的每页条目数 var detect = function (width) { var count; if (width < 576) { count = 6; } else if (width >= 576 && width < 768) { count = 8; } else if (width >= 768 && width < 992) { count = 12; } else if (width >= 992) { count = 16; } return count; } // 封装分页初始化函数,方便初始加载和resize时重复调用 function initPagination() { var pageWidth = window.innerWidth; var itemsPerPage = detect(pageWidth); // 先销毁已有的分页实例,避免重复初始化冲突 if ($("#content").data('flexiblePagination')) { $("#content").flexiblePagination('destroy'); } // 用最新的配置重新初始化分页 $("#content") .flexiblePagination({ itemsPerPage: itemsPerPage, displayedPages: 4, itemSelector: "div.result:visible", pagingControlsContainer: "#pagingControls", showingInfoSelector: "#showingInfo", searchBox: { onClick: !0, onClickSelector: "#search" }, }) .getController().onPageClick = function (s, n) { console.log("You Clicked Page: " + s); }; } // 添加防抖函数,避免resize频繁触发重绘导致页面卡顿 function debounce(fn, delay) { var timer = null; return function() { clearTimeout(timer); timer = setTimeout(fn, delay); } } $(document).ready(function() { // 页面加载完成后先初始化一次分页 initPagination(); // 窗口尺寸变化时,防抖调用重新初始化分页 $(window).resize(debounce(initPagination, 200)); });
内容的提问来源于stack exchange,提问作者harish
相关产品推荐
相关产品推荐

