在网页开发中,动态更新元素样式是常见需求,例如根据用户当前位置高亮显示导航菜单。本文介绍如何利用aria-current="page" 问题: 假设我们有一个导航栏HTML片段:巧用aria-current属性,动态调整导航链接样式
<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>aria-current="page"<https:>属性标识当前激活的链接,但其位置会根据用户访问页面而变化。我们需要一种方法动态地为拥有该属性的<a><https:>标签添加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>提供了解决方案。我们可以利用[aria-current="page"]<https:>选择器直接选中带有aria-current="page"<https:>属性的<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>这段代码会使所有带有aria-current="page"<https:>属性的元素字体加粗(font-weight: 600<https:>相当于中等粗细)。 你也可以选择添加font-medium<https:>类名,然后在你的样式表中定义.font-medium { font-weight: 600; }<https:>。 选择哪种方式取决于你的项目CSS结构和命名规范。直接设置样式更简洁,而使用类名则更易于管理和复用。<https:><p>通过这种方法,我们无需JavaScript代码,就能根据aria-current="page"<https:>属性动态地为导航链接添加样式,简洁高效地利用了HTML和CSS的特性。<https:></https:></https:></p></https:></https:></https:></https:></https:></p></https:>
以上就是如何利用aria-current属性动态为导航链接添加样式?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号