实现分页功能【jQuery】
效果:
分页功能:
页码分屏展示,当前示例一屏为5页,左右箭头为可以切换上一屏、下一屏
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>分页</title><script src="./js/jquery-1.7.2.min.js"></script>
</head>
<style>#pagination {width: 210px;padding-top: 10px;display: flex;justify-content: center;position: absolute;bottom: 10px;//width: calc(100% - 20px); //外层有父元素固定长度}#pagination .page_list_box {flex: 1;overflow: hidden;}#pagination .page_list {display: flex;transform: translateX(0px);}#pagination span {width: 24px;height: 24px;flex-shrink: 0;font-size: 12px;text-align: center;line-height: 24px;border: 1px solid #ddd;border-radius: 4px;cursor: pointer;margin-right: 4px;position: relative;}#pagination span.disabled {background: #eee;cursor: not-allowed;}#pagination span.active {border-color: #3b84ec;color: #3b84ec;font-weight: 600;}#pagination span:not(.disabled):hover {border-color: #3b84ec;}#pagination .page_left::before {content: '';position: absolute;top: 0;left: 0;right: 0;bottom: 0;background: url(./images/arrow_left.png) no-repeat center;background-size: 70%;}#pagination .page_right::before {content: '';position: absolute;top: 0;left: 0;right: 0;bottom: 0;background: url(./images/arrow_right.png) no-repeat center;background-size: 70%;}
</style>
<body><!-- 分页 --><div id="pagination"><span class="page_left disabled" onclick="pagetrans(this,'pre')"></span><div class="page_list_box"><div class="page_list"></div></div><span class="page_right" onclick="pagetrans(this,'next')"></span></div>
</body>
<script>//当前页码
var currentPage = 1;
//页数
var pageLength = 10;
//滑动距左的页数
var currentleft = 0
renderPage()
function renderPage(){$(".page_list").empty()var pageStr = ''for (let i = 0; i < pageLength; i++) {pageStr += '<span onClick="pageClick(this)">'+ (i * 1 + 1)+'</span>'}$(".page_list").append(pageStr)$(".page_list span").eq(currentPage - 1).addClass("active")if(pageLength == 1) {$(".page_right").addClass('disabled')}
}
function pageClick(object){if(object.innerText == currentPage) returncurrentPage = object.innerText$(object).addClass("active").siblings().removeClass("active")renderHistorys()
}
function pagetrans(object,type) {if($(object).hasClass('disabled')) returnleftLength = Math.ceil(pageLength / 5)var currentNum = $(".page_list")[0].style.transform ? $(".page_list")[0].style.transform.split('px')[0].split("(")[1] : '0'if(type == 'pre') {if(currentleft > 0) {var num = (currentNum * 1 + 150) + 'px'$(".page_list").css("transform","translateX("+num+")")currentleft--if(currentleft == 0) {$(".page_left").addClass('disabled')}if(currentleft < leftLength - 1) {$(".page_right").removeClass('disabled')}}}else {if(currentleft < leftLength - 1) {var num = (currentNum * 1 - 150) + 'px'$(".page_list").css("transform","translateX("+num+")")currentleft++if(currentleft > 0) {$(".page_left").removeClass('disabled')}if(currentleft == leftLength - 1) {$(".page_right").addClass('disabled')}}}
}
</script>
</html>