在网页开发中,动态更新元素样式是常见需求,例如根据用户当前位置高亮显示导航菜单。本文介绍如何利用
巧用aria-current属性,动态调整导航链接样式
aria-current="page"<https:>属性,无需JavaScript,仅用CSS就能优雅地为活动导航链接添加<code>font-medium<https:>样式。<https:><p><strong>问题:<https:><https:><p>假设我们有一个导航栏HTML片段:<https:><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;"><div class="nav" id="nav">
<a class="group relative px-4" href="https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712">home<https:><a class="group relative px-4" href="https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712pricing">pricing<https:><a class="group relative px-4" href="https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712story">our story<https:><a aria-current="page" class="group relative px-4" href="https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712blog">blog<https:><https:><https:><p><code>aria-current="page"<https:>属性标识当前激活的链接,但其位置会根据用户访问页面而变化。我们需要一种方法动态地为拥有该属性的<code><a><https:>标签添加<code>font-medium<https:>样式。<https:><p><strong>解决方案:<https:><https:><p>CSS<a style="color:#f60; text-decoration:underline;" title="属性选择器" href="https://www.php.cn/zt/70573.html" target="_blank">属性选择器</a>提供了解决方案。我们可以利用<code>[aria-current="page"]<https:>选择器直接选中带有<code>aria-current="page"<https:>属性的<code><a><https:>标签,并设置其样式。<https:><p>以下CSS代码即可实现:<https:><pre class="brush:php;toolbar:false;">[aria-current="page"] {
font-weight: 600; https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712* 或添加类名:class="font-medium" *https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712
}<https:><p>这段代码会使所有带有<code>aria-current="page"<https:>属性的元素字体加粗(<code>font-weight: 600<https:>相当于中等粗细)。 你也可以选择添加<code>font-medium<https:>类名,然后在你的样式表中定义<code>.font-medium { font-weight: 600; }<https:>。 选择哪种方式取决于你的项目CSS结构和命名规范。直接设置样式更简洁,而使用类名则更易于管理和复用。<https:><p>通过这种方法,我们无需JavaScript代码,就能根据<code>aria-current="page"<https:>属性动态地为导航链接添加样式,简洁高效地利用了HTML和CSS的特性。<https:></https:></https:></code></p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1297">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680203824948.png" alt="西语写作助手">
</a>
<div class="aritcle_card_info">
<a href="/ai/1297">西语写作助手</a>
<p>西语助手旗下的AI智能写作平台,支持西语语法纠错润色、论文批改写作</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="西语写作助手">
<span>21</span>
</div>
</div>
<a href="/ai/1297" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="西语写作助手">
</a>
</div>
</https:></https:></code></https:></code></https:></code></https:></code></p></https:></pre>
以上就是如何利用aria-current属性动态为导航链接添加样式?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号