纯CSS导航选中高亮是指使用CSS来实现导航栏中当前选中项的高亮显示效果。这种效果通常用于突出显示用户当前所在的页面或功能模块。
:hover
、:active
、:focus
等伪类来实现高亮效果。适用于各种网页导航栏,如网站顶部导航、侧边栏导航等。
以下是一个基于伪类的纯CSS导航选中高亮示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>纯CSS导航选中高亮</title>
<style>
.nav {
display: flex;
list-style: none;
padding: 0;
}
.nav li {
margin-right: 20px;
}
.nav a {
text-decoration: none;
color: #333;
}
.nav a:hover,
.nav a:focus {
color: #f00;
font-weight: bold;
}
</style>
</head>
<body>
<ul class="nav">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</body>
</html>
如果需要更复杂的选中高亮逻辑,可以结合JavaScript来实现。例如,通过监听路由变化来动态添加或移除高亮类名。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>纯CSS导航选中高亮</title>
<style>
.nav {
display: flex;
list-style: none;
padding: 0;
}
.nav li {
margin-right: 20px;
}
.nav a {
text-decoration: none;
color: #333;
}
.active {
color: #f00;
font-weight: bold;
}
</style>
</head>
<body>
<ul class="nav">
<li><a href="#home" class="active">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<script>
const links = document.querySelectorAll('.nav a');
const currentPath = window.location.hash;
links.forEach(link => {
if (link.getAttribute('href') === currentPath) {
link.classList.add('active');
}
});
</script>
</body>
</html>
通过这种方式,可以实现更精确的导航选中高亮效果。
领取专属 10元无门槛券
手把手带您无忧上云