css 保持当前按钮分页突出显示

jc3wubiy  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(119)

我正在开发一个React应用程序,并且只使用CSS,我试图在更改页面时用不同的颜色选择分页按钮,以便当前页面保持选中状态。
但我没有得到它,即使与其他问题,我已经检查。
当我单击按钮时,它会改变颜色,但不会一直显示。
我的分页和CSS看起来像这样:

<div className={style.Pagination_numbers}>
      <ul className={style.Pagination__ul}>
        {pageNumbers?.map((number) => {
          return (
            //loop for the pageNumbers
          <li className={style.list}>
            <button onClick={() => pagination(number)}>{number}</button>
          </li>)
          })}
      </ul>
      <button className={style.backButton} onClick={prevPage}>Back</button>
      <button className={style.advanceButton} onClick={nextPage}>Next</button>
    </div>

CSS:

.list > button {
    height: 35px;
    width: 35px;
    margin: 5px;
    bottom: 19px;
    border-radius: 25px;
    font-weight: 200;
    left: 135px;
    color: rgb(255, 255, 255);
    cursor: pointer;
    background-color: #000000a2;
    position: relative;
    flex-direction: row;
}

.list > button:hover {
    color: rgb(255, 255, 255);
}

.list > button:active {
    position: relative;
    color: rgb(255, 255, 255);
    background-color: rgb(71, 117, 218);
}
vwkv1x7d

vwkv1x7d1#

一旦页面被选中,您希望按钮样式保持不同(这里类似于:active伪类)。
不幸的是,仅有CSS是不够的:它只能基于一些即时事件(如:hover:active)或在某种程度上基于导航历史(具有:visited伪类)来进行样式化,但这将匹配 * 所有 * 先前访问的页面,而不仅仅是当前页面。
要实现"仅当前选中页面"上的样式,需要一个state来存储当前选中页面的信息,然后根据该状态,可以有条件地将样式应用到特定的页面按钮(当前页面对应的按钮)上,例如使用一个类:(下面的代码段假设您使用带有钩子的React功能组件)

function App() {
  const pageNumbers = [1, 2, 3, 4];

  // State to store the currently selected page
  const [page, setPage] = React.useState(null);

  function pagination(number) {
    // Record the selected page in state
    setPage(number);
  }

  return (
    <ul>
      {pageNumbers?.map((number) => (
        //loop for the pageNumbers
        <li className="list">
          <button
            onClick={() => pagination(number)}
            // Apply an "active" class
            // if page is selected
            className={number === page ? "active" : ""}
          >
            {number}
          </button>
        </li>
      ))}
    </ul>
  );
}
.list > button:active,
/* Also select button with "active" class */
.list > button.active {
  position: relative;
  color: rgb(255, 255, 255);
  background-color: rgb(71, 117, 218);
}

演示:https://codepen.io/ghybs/pen/gOjLgxR

相关问题