使用 :target 伪类可实现锚点高亮,通过匹配 URL 中的 fragment 标识符来选中目标元素并应用样式,如改变背景色、添加边框或结合动画提升视觉反馈,常用于文档或单页应用中,无需 JavaScript 即可增强用户体验。

当用户点击页面内的锚点链接时,可以通过 CSS 的 :target 伪类来高亮显示对应的目标元素。这种效果常用于文档、帮助页面或单页应用中,让用户清楚地看到跳转到了哪个部分。
:target 是一个 CSS 伪类,它匹配当前 URL 中 fragment 标识符(即 # 后面的部分)所指向的元素。例如,URL 为 example.com#section1 时,#section1 就是目标,而 id 为 section1 的元素就会被 :target 选中。
只需要为带有 id 的目标元素设置 :target 样式即可实现高亮:
<style>
section:target {
background-color: yellow;
padding: 10px;
border-left: 4px solid orange;
}
</style>
<p><a href="#section1">跳转到第一节</a>
<a href="#section2">跳转到第二节</a></p><p><section id="section1">
<h3>第一节内容</h3>
<p>这里是第一部分内容。</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>
</section></p><p><section id="section2">
<h3>第二节内容</h3>
<p>这里是第二部分内容。</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/2221">
<img src="https://img.php.cn/upload/ai_manual/001/246/273/68b6c52f05eb9477.png" alt="巧文书">
</a>
<div class="aritcle_card_info">
<a href="/ai/2221">巧文书</a>
<p>巧文书是一款AI写标书、AI写方案的产品。通过自研的先进AI大模型,精准解析招标文件,智能生成投标内容。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="巧文书">
<span>281</span>
</div>
</div>
<a href="/ai/2221" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="巧文书">
</a>
</div>
</section></p>可以根据设计需求选择不同的视觉反馈方式:
section {
scroll-margin-top: 60px; /* 留出固定头部的空间 */
}
可以结合 transition 或 animation 制作更自然的提示效果:
section:target {
animation: highlight 1s ease-in-out;
}
<p>@keyframes highlight {
0% { background-color: #ff0; }
100% { background-color: #fff; }
}</p>这样会在跳转后短暂闪烁黄色背景,再恢复,引导用户注意力。
基本上就这些。使用 :target 实现锚点高亮简单高效,无需 JavaScript,兼容性也很好。关键是确保目标元素有正确的 id,并合理设计样式提升可读性。
以上就是如何用css :target制作锚点高亮效果的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号