分页页码显示效果

自己写代码实现了一个分页器效果,记录一下

在线演示

https://www.zhaojun.ink/demo/page.html

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }

        .page {
            list-style-type: none;
            display: flex;
            gap: 10px;
        }

        .page a {
            padding: 4px 8px;
            color: #777;
            cursor: pointer;
            border: solid 1px #e2e2e2;
            border-radius: 2px;
            text-decoration: none;
            transition: all 300ms;
            user-select: none;
        }

        .page li:hover a {
            background-color: #2b88f0;
            color: #fff;
            border: solid 1px #2b88f0;
        }

        .page li.active a {
            background-color: #2b88f0;
            color: #fff;
            border: solid 1px #2b88f0;
        }
    </style>
</head>
<body>
<ul class="page"></ul>

<script>
    let totalPage = 20
    let maxShow = 10
    let currentPage = 1


    function renderPageHandle(currentPage) {
        renderPage(totalPage, currentPage, maxShow)
    }

    function renderPage(totalPage, currentPage, maxShow) {
        let prePage = `<li><a onclick="prev()">上一页</a></li>`
        let nextPage = `<li><a onclick="next()">下一页</a></li>`
        let pageTemplate = ''
        let middle = Math.floor(maxShow / 2)
        let count = 1
        let start
        if (currentPage <= middle) {
            start = 1
        } else if (currentPage >= totalPage - middle) {
            start = totalPage - maxShow + 1
        } else {
            start = currentPage - middle + 1
        }
        while (count <= maxShow && start <= totalPage) {
            pageTemplate += `<li class="${start === currentPage ? 'active' : ''}"><a onclick="jump(${start})">${start}</a></li>`
            if (count === maxShow) {
                break
            }
            start++
            count++
        }
        document.querySelector('.page').innerHTML = prePage + pageTemplate + nextPage
    }

    function prev() {
        if (currentPage === 1) {
            return
        }
        currentPage--
        renderPageHandle(currentPage)
    }

    function next() {
        if (currentPage === totalPage) {
            return
        }
        currentPage++
        renderPageHandle(currentPage)
    }

    function jump(page) {
        currentPage = page
        renderPageHandle(currentPage)
    }

    renderPageHandle(currentPage)
</script>
</body>
</html>

Pasted image 20231113101825


分页页码显示效果
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/page-demo
作者
卑微幻想家
发布于
2023-11-13
许可协议