
巧用aria-current属性,动态调整导航链接样式
在网页开发中,动态更新元素样式是常见需求,例如根据用户当前位置高亮显示导航菜单。本文介绍如何利用aria-current="page"属性,无需JavaScript,仅用CSS就能优雅地为活动导航链接添加font-medium样式。
问题:
假设我们有一个导航栏HTML片段:
<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/2405"> <img src="https://img.php.cn/upload/ai_manual/001/246/273/176395441542705.png" alt="大师兄智慧家政"> </a> <div class="aritcle_card_info"> <a href="/ai/2405">大师兄智慧家政</a> <p>58到家打造的AI智能营销工具</p> <div class=""> <img src="/static/images/card_xiazai.png" alt="大师兄智慧家政"> <span>99</span> </div> </div> <a href="/ai/2405" 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:>
以上就是如何利用aria-current属性动态为导航链接添加样式?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1113818.html
微信扫一扫
支付宝扫一扫