网页开发中,根据页面状态动态调整元素样式非常常见。本文将演示如何利用
巧用aria-current属性,动态调整导航链接样式
aria-current="page"<https:>属性,为当前激活的导航链接添加<code>font-medium<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:>属性清晰地标识了当前激活的链接。 接下来,我们将通过CSS或JavaScript来实现样式的动态添加。<https:><p><strong>方法一:纯CSS方案 (推荐)<https:><https:><p>这是最简洁高效的方法,直接利用CSS<a style="color:#f60; text-decoration:underline;" title="属性选择器" href="https://www.php.cn/zt/70573.html" target="_blank">属性选择器</a>:<https:><pre class="brush:php;toolbar:false;">[aria-current="page"] {
font-weight: 500; https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712* 等同于font-medium *https://www.php.cn/link/29a9f8c8460e5e2be4edde557fd83712
}<https:><p>这段CSS代码会自动作用于带有<code>aria-current="page"<https:>属性的<code><a><https:>标签,无需任何JavaScript代码。<https:><p><strong>方法二:JavaScript动态添加类名<https:><https:><p>如果你的样式调整逻辑较为复杂,或者需要与其他JavaScript代码交互,则可以使用JavaScript动态添加类名:<https:><pre class="brush:php;toolbar:false;">const currentLink = document.querySelector('[aria-current="page"]');
if (currentLink) {
currentLink.classList.add('font-medium');
}<https:><p>这段代码首先使用<code>querySelector<https:>选择器找到带有<code>aria-current="page"<https:>属性的元素,然后使用<code>classList.add()<https:>方法添加<code>font-medium<https:>类名。 记得在你的CSS中定义<code>.font-medium<https:>类样式。<https:><p>两种方法都能实现目标,选择哪种取决于你的项目需求和复杂度。 对于简单的样式调整,纯CSS方案更简洁易维护;而对于复杂的场景,JavaScript方案则提供了更大的灵活性。<https:></https:></p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/947">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680000018617.png" alt="沉浸式翻译">
</a>
<div class="aritcle_card_info">
<a href="/ai/947">沉浸式翻译</a>
<p>沉浸式翻译:全网口碑炸裂的双语对照网页翻译插件</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="沉浸式翻译">
<span>83</span>
</div>
</div>
<a href="/ai/947" 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></https:></code></p></https:></pre>
以上就是如何利用aria-current属性动态控制网页导航链接的字体样式?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号