纯CSS页面切换是指使用CSS来实现页面之间的切换效果,而不依赖JavaScript或其他脚本语言。这种技术主要依赖于CSS的动画、过渡和伪类等特性。
:hover
、:active
等伪类来实现简单的页面切换效果。以下是一个简单的基于伪类的页面切换示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Page Switch</title>
<style>
.page {
display: none;
}
.page.active {
display: block;
}
.nav {
display: flex;
justify-content: center;
margin-top: 20px;
}
.nav a {
margin: 0 10px;
text-decoration: none;
color: black;
}
.nav a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="nav">
<a href="#" class="active">Page 1</a>
<a href="#">Page 2</a>
<a href="#">Page 3</a>
</div>
<div class="page active" id="page1">
<h1>Page 1</h1>
<p>This is the first page.</p>
</div>
<div class="page" id="page2">
<h1>Page 2</h1>
<p>This is the second page.</p>
</div>
<div class="page" id="page3">
<h1>Page 3</h1>
<p>This is the third page.</p>
</div>
<script>
document.querySelectorAll('.nav a').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
document.querySelectorAll('.page').forEach(page => {
page.classList.remove('active');
});
document.querySelectorAll('.nav a').forEach(a => {
a.classList.remove('active');
});
e.target.classList.add('active');
document.getElementById(e.target.getAttribute('href').substring(1)).classList.add('active');
});
});
</script>
</body>
</html>
will-change
属性来提示浏览器提前优化某些元素。通过以上方法,可以有效解决纯CSS页面切换中常见的问题,提升用户体验和页面性能。