js操作dom节点实现分页(js原生)

js代码

/**
 * 
 * @param {*} currentPage  当前点击的页码
 * @param {*} pagenum           总页码
 * @param {*} selectorLength    中间显示多少个
 * @param {*} domId             需要渲染的dom的Id
 */
function createPageSelector(currentPage,pagenum,selectorLength,domId){

    /*
        
    */

   const divPageSelector = document.getElementById(domId)

   divPageSelector.innerHTML =''
   /**
    * 
    * @param {*} className  // 样式名字
    * @param {*} text       // 内容
    * @param {*} clickpage  // 点击的页码
    */
    function createElpage(className,text,clickpage){  // 创建 a 标签 
        const a = document.createElement('a')
        a.className =className
        a.innerText =text
        divPageSelector.appendChild(a)
        
        a.onclick = function() {
            createPageSelector(clickpage,pagenum,selectorLength,domId)
        }
    }

    // 1. 左边 首页 上一页
    if(currentPage ==1){
        createElpage('disabled','首页',1);
        createElpage('disabled','上一页',currentPage-1)
    }else if(currentPage>1){
        createElpage('','首页',1);
        createElpage('','上一页',currentPage-1)
    }
        
    // 2. 中间 页码显示
    let firstpage =Math.floor(currentPage -selectorLength/2)
    if(firstpage<1){
        firstpage=1
    }
    let lastpage = Math.floor(firstpage+selectorLength -1)
    if(lastpage>pagenum){
        lastpage = pagenum
        firstpage =lastpage-selectorLength+1
    }
    for(let i =firstpage;i<=lastpage;i++){
        if(i == currentPage){
            createElpage('active',i,i)
        }else{
            createElpage('',i,i)
        }
        
    }

    // 3. 右边 下一页 尾页
    if(currentPage == pagenum){
        createElpage('disabled','下一页',currentPage+1);
        createElpage('disabled','尾页',pagenum)
    }else{
        createElpage('','下一页',currentPage+1);
        createElpage('','尾页',pagenum)
    }
        
    // 4. 页码标识
    const span =document.createElement('span')
    span.innerHTML = currentPage + ' / ' +pagenum
    divPageSelector.appendChild(span)
}
#page {
    text-align: center;
}

#page a {
    border: 1px solid #e1e2e3;
    color: #001ac4;
    height: 34px;
    display: inline-block;
    padding: 0 12px;
    margin:  8px;
    line-height: 34px;
    cursor: pointer;
    user-select: none;
}

#page a.active {
    color: orange;
    cursor: none;
}

#page a.disabled {
    color:#ccc;
    cursor: not-allowed;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值