<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>html导航栏页面切换效果减少代码量</title>
<style>
body {
background: #0b1b2c;
/* 默认背景色 */
color: #ffffff;
/* 默认文字颜色 */
transition: background-color 0.3s, color 0.3s;
/* 过渡效果 */
}
nav {
background-color: #cbcbcb;
padding: 5px;
}
nav a {
padding: 4px 8px;
text-decoration: none;
transition: background-color 0.3s;
}
nav a:hover {
background-color: #575757;
}
.nav-active {
background-color: #007BFF;
color: white;
text-shadow: 1px 1px 1px #000000;
}
.content {
display: none;
padding: 20px;
}
.content p {
background-color: #144756;
color: #f56c6c;
text-shadow: 1px 1px 1px #000000;
}
.active {
display: block;
}
body.day-mode {
background-color: #f0f0f0;
color: #000000;
}
nav.day-mode {
background-color: #cccccc;
}
.toggle-day-mode {
float: right;
}
</style>
</head>
<body>
<nav>
<a href="#" onclick="showPage('home')">首页</a>
<a href="#" onclick="showPage('services')">服务</a>
<a href="#" onclick="showPage('contact')">联系</a>
<a href="#" onclick="showPage('about')">关于我们</a>
<a href="#" class="toggle-day-mode" onclick="toggledayMode()">切换白天模式</a> <!-- 添加白天模式切换链接 -->
</nav>
<div id="home" class="content active">
<h1>欢迎来到首页</h1>
<p>这是首页的内容。</p>
</div>
<div id="about" class="content">
<h1>关于我们</h1>
<p>这是关于我们的内容。</p>
</div>
<div id="services" class="content">
<h1>服务</h1>
<p>这是服务的内容。</p>
</div>
<div id="contact" class="content">
<h1>联系</h1>
<p>这是联系的内容。</p>
</div>
</body>
<script>
// 页面切换函数
function showPage(page) {
// 隐藏所有内容并移除激活样式
document.querySelectorAll('.content').forEach(content => content.classList.remove('active'));
document.querySelectorAll('nav a').forEach(link => link.classList.remove('nav-active'));
// 显示当前选择的内容
const selectedContent = document.getElementById(page);
selectedContent.classList.add('active');
document.querySelector(`nav a[onclick="showPage('${page}')"]`).classList.add('nav-active');
}
// 切换白天模式函数
function toggledayMode() {
document.body.classList.toggle('day-mode');
document.querySelector('nav').classList.toggle('day-mode');
}
</script>
<!-- <script>
// 处理导航点击事件
function handleNavClick(event) {
const target = event.target;
if (target.tagName === 'A' && target.dataset.page) {
showPage(target.dataset.page);
}
}
// 页面切换函数
function showPage(page) {
document.querySelectorAll('.content').forEach(content => content.classList.remove('active'));
document.querySelectorAll('nav a').forEach(link => link.classList.remove('nav-active'));
document.getElementById(page).classList.add('active');
document.querySelector(`nav a[data-page="${page}"]`).classList.add('nav-active');
}
// 切换白天模式函数
function toggledayMode() {
document.body.classList.toggle('day-mode');
document.querySelector('nav').classList.toggle('day-mode');
} -->
</script>
</html>