没有 Javascript 的分页

Pagination without Javascript

我正在尝试创建页码并发现了这个有趣的 codePen:https://codepen.io/p-ziegler/pen/bmdaaN

.b,
input[type="radio"] {
    display: inline-block;
    width: 16px;
    height: 16px;
    vertical-align: middle;
}

.b {
    background-color: gray;
    text-align: center;
    color: white;
}

input[type="radio"] {
    opacity: 0.01;
    margin-left: -16px;
    cursor: pointer;
}

.p {
    display: none;
}

#p1:checked ~ .p1,
#p2:checked ~ .p2,
#p3:checked ~ .p3 {
    display: block;
}
<div>
    <div class="b">1</div><input type="radio" name="p" id="p1" checked>
    <div class="b">2</div><input type="radio" name="p" id="p2">
    <div class="b">3</div><input type="radio" name="p" id="p3">
    <div class="p p1">Page 1</div>
    <div class="p p2">Page 2</div>
    <div class="p p3">Page 3</div>
</div>

我喜欢这里不需要 Javascript。但问题是我想将页码切换到内容下方的底部,并将内容设置在页码上方。但是当我切换它们时,所有内容都消失了。你能告诉我如何让它工作吗?

正如我在评论中提到的,管理路线的更好方法是在无线电输入中使用 CSS 中的 :target 伪 class。 这样你就不需要担心你的来源顺序 HTML。 该解决方案的一个常见问题是默认页面。 请参阅下面带有默认页面(主页)的代码片段的工作示例。

在此代码中,我们隐藏了所有部分。然后我们使默认页面可见(在本例中为 #home),然后在满足 :target 选择器时再次隐藏默认块。 这些选择器的特殊性对于确保默认部分在被选中时不被隐藏非常重要。

/* hide all by default */
section {
    display: none;
}
/* show home by default */
#page1 {
    display: block;
}
/* on target show */
section:target {
    display: block;
}
/* on target hide all siblings that are the default, if default is select itself it won't have sibling called home */
section:target ~ #page1 {
    display: none;
}


/* The below is just for styling */
nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
nav ul li {
    display: inline-block;
}
nav ul li a {
    background: gray;
    color: white;
    padding: 0.25rem;
    text-decoration: none;
}
<!DOCTYPE html>
<html>
<head>
    <title>CSS only SPA</title>
</head>
<body>
    <nav>
        <ul>
            <li>
                <a href="#page1">1</a>
            </li>
            <li>
                <a href="#page2">2</a>
            </li>
            <li>
                <a href="#page3">3</a>
            </li>
        </ul>
    </nav>

    <main>
        <section id="page3">
            <h1>Page 3</h1>
            <p>
                Proin ante arcu, hendrerit ac diam sagittis, sollicitudin posuere ante. Etiam egestas eros at nunc venenatis eleifend eu at tellus.
            </p>
        </section>

        <section id="page2">
            <h1>Page 2</h1>
            <p>
                Integer porttitor vitae est vel suscipit. Fusce placerat justo at libero aliquam maximus.
            </p>
        </section>
        
        <section id="page1">
            <h1>Page 1</h1>
            <p>
                Ut aliquet sit amet urna non porta. Maecenas dignissim, sem eget pulvinar luctus, ex dolor posuere magna, ut elementum quam eros vel nulla.
            </p>
        </section>
    </main>
</body>
</html>