HTML代码:

<div class="pagination">
  <button class="prev-btn">&lt;</button>
  <div class="page-wrapper">
    <button class="page-btn active">1</button>
    <button class="page-btn">2</button>
    <button class="page-btn">3</button>
  </div>
  <button class="next-btn">&gt;</button>
</div>

CSS代码:

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}

.page-wrapper {
  display: flex;
}

.page-btn {
  margin: 0 10px;
  padding: 5px 10px;
  border: none;
  background-color: transparent;
  color: #333;
  cursor: pointer;
}

.page-btn.active {
  border: 1px solid #333;
}

.prev-btn, .next-btn {
  margin: 0 10px;
  padding: 5px 10px;
  border: none;
  background-color: transparent;
  color: #333;
  cursor: pointer;
}

.prev-btn:hover, .next-btn:hover {
  color: #666;
}

JavaScript代码:

const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
const pageBtns = document.querySelectorAll('.page-btn');

let currentPage = 0;

prevBtn.addEventListener('click', () => {
  if (currentPage > 0) {
    currentPage--;
    updatePagination();
  }
});

nextBtn.addEventListener('click', () => {
  if (currentPage < pageBtns.length - 1) {
    currentPage++;
    updatePagination();
  }
});

pageBtns.forEach((btn, index) => {
  btn.addEventListener('click', () => {
    currentPage = index;
    updatePagination();
  });
});

function updatePagination() {
  pageBtns.forEach((btn, index) => {
    if (index === currentPage) {
      btn.classList.add('active');
    } else {
      btn.classList.remove('active');
    }
  });
}

在JavaScript代码中,我们首先获取到了左右按钮和每个页码按钮的DOM元素。然后,我们定义了一个currentPage变量来存储当前选中的页码。我们给左右按钮和每个页码按钮都添加了点击事件监听器,当点击时,我们根据需要更新currentPage变量的值,然后调用updatePagination函数来更新页码的样式。

updatePagination函数首先遍历所有页码按钮,如果当前按钮的索引和currentPage相等,则给它添加active类名,否则移除active类名。这样我们就可以通过改变currentPage变量的值来动态更新页码的样式了

js和html写一个底部可以自己选择某一页的三个分页出来可以用左右按钮控制切换哪一页也可以用左右按钮控制且左按钮在页码左边右按钮在页码右边并且下面的页码会被一个有颜色的框框围起来跳转的时会随之变化

原文地址: https://www.cveoy.top/t/topic/fP2F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录