导航点击后变色是一种常见的网页交互效果,用于提示用户当前所处的页面位置。这种效果通常通过CSS来实现。
:active
和:focus
来实现点击后的颜色变化。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>导航点击后变色</title>
<style>
.nav-item {
padding: 10px;
color: #fff;
background-color: #333;
margin: 5px;
cursor: pointer;
}
.nav-item:hover,
.nav-item:focus {
background-color: #555;
}
.nav-item:active {
background-color: #777;
}
</style>
</head>
<body>
<div class="nav">
<div class="nav-item" tabindex="0">Home</div>
<div class="nav-item" tabindex="0">About</div>
<div class="nav-item" tabindex="0">Services</div>
<div class="nav-item" tabindex="0">Contact</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>导航点击后变色</title>
<style>
.nav-item {
padding: 10px;
color: #fff;
background-color: #333;
margin: 5px;
cursor: pointer;
}
.active {
background-color: #777;
}
</style>
</head>
<body>
<div class="nav">
<div class="nav-item" onclick="changeColor(this)">Home</div>
<div class="nav-item" onclick="changeColor(this)">About</div>
<div class="nav-item" onclick="changeColor(this)">Services</div>
<div class="nav-item" onclick="changeColor(this)">Contact</div>
</div>
<script>
function changeColor(element) {
const items = document.querySelectorAll('.nav-item');
items.forEach(item => item.classList.remove('active'));
element.classList.add('active');
}
</script>
</body>
</html>
通过以上示例代码,你可以实现导航点击后变色的效果。纯CSS实现简单且性能较好,而JavaScript辅助可以实现更复杂的交互效果。
领取专属 10元无门槛券
手把手带您无忧上云