您的位置:首頁技術文章
文章詳情頁

js實現簡單的前端分頁效果

瀏覽:97日期:2024-03-21 11:45:23

有些項目業務比較簡單,但用到前端分頁的地方又比較多,插件的體積比較難控制用起來也麻煩,所以自己寫一個簡易的。

實現思路

通過 jQuery.slice() 選擇子集的區間元素, 然后控制顯示隱藏來實現;假設每頁顯示數量為x,當前頁碼為y,元素索引從0開始,那么顯示的區間即為 x(y-1) 到 xy。

效果演示

js實現簡單的前端分頁效果

demo代碼

<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>前端分頁實現demo</title></head><body> <div class='parent'><ul style='min-height: 147px;'></ul><div class='page-box'> <button class='page-btn prev'>上一頁</button> <span class='page-num'>1/1</span> <button class='page-btn next'>下一頁</button></div> </div> <div class='parent'><ul style='min-height: 63px;'></ul><div class='page-box'> <button class='page-btn prev'>上一頁</button> <span class='page-num'>1/1</span> <button class='page-btn next'>下一頁</button></div> </div> <script src='https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js'></script> <script>/** * 分頁初始化 * @param {*} eleBox 需要被分頁的容器 * @param {*} size 每頁的條數 */function InitPagination(eleBox, size) { var box = $(eleBox),children = box.children(),total = children.length,pageBox = box.next(),pageNum = pageBox.find(’.page-num’),maxNum = !Math.ceil(total / size) ? 1 : Math.ceil(total / size); pageNum.text(’1/’ + maxNum); children.hide(); children.slice(0, size).show(); pageBox.off().on(’click’, ’.prev, .next’, function (e) {var nowNum = parseInt(pageNum.text().split(’/’)[0]);if ($(this).hasClass(’prev’)) { nowNum--; if (nowNum < 1) {nowNum = 1return; }} else { nowNum++; if (nowNum > maxNum) {nowNum = maxNumreturn; }}children.hide();children.slice(size * (nowNum - 1), nowNum * size).show();pageNum.text(nowNum + ’/’ + maxNum); })}// 模擬數據寫入var box = $(’.box’), box2 = $(’.box2’), li = ’’;for (let i = 0; i < 16; i++) { li += ’<li>’ + i + ’</li>’}box.html(li); box2.html(li);// 實例化分頁器new InitPagination(box, 7)new InitPagination(box2, 3) </script></body></html>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: JavaScript
相關文章:
国产综合久久一区二区三区