制作具有多位置锚点的导航栏效果,可以使用CSS中的伪类:target
。首先,为每个目标位置添加一个ID,例如:
<h3 id="section1">Section 1</h3>
<p>Content for section 1 goes here...</p>
<h3 id="section2">Section 2</h3>
<p>Content for section 2 goes here...</p>
<h3 id="section3">Section 3</h3>
<p>Content for section 3 goes here...</p>
然后,在导航栏中创建链接,链接到相应的目标位置,并使用:target
伪类来添加样式。例如:
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
</nav>
/* 首先,隐藏所有内容 */
p {
display: none;
}
/* 然后,对被锚点的目标位置应用样式 */
:target p {
display: block;
}
/* 添加一些样式来突出显示当前活动链接 */
nav a:target {
font-weight: bold;
color: red;
}
这样,当用户点击导航栏中的链接时,页面将自动滚动到相应的目标位置,并显示相应的内容。
完整的示例代码如下:
<h3 id="section1">Section 1</h3>
<p>Content for section 1 goes here...</p>
<h3 id="section2">Section 2</h3>
<p>Content for section 2 goes here...</p>
<h3 id="section3">Section 3</h3>
<p>Content for section 3 goes here...</p>
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
</nav>
<style>
p {
display: none;
}
:target p {
display: block;
}
nav a:target {
font-weight: bold;
color: red;
}
</style>