"楼层点亮"通常是指在网页设计中,通过JavaScript实现页面滚动时,对应楼层的导航链接高亮显示的效果。这种效果可以提升用户体验,让用户清楚地知道当前所处的位置。
以下是一个简单的JavaScript实现楼层点亮的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>楼层点亮示例</title>
<style>
body {
font-family: Arial, sans-serif;
}
.section {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
border-bottom: 1px solid #ccc;
}
.nav {
position: fixed;
top: 0;
width: 100%;
background: #fff;
padding: 10px;
text-align: center;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.nav a {
margin: 0 10px;
text-decoration: none;
color: #333;
}
.nav a.active {
color: #f00;
}
</style>
</head>
<body>
<div class="nav">
<a href="#section1" class="active">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</div>
<div id="section1" class="section">Section 1</div>
<div id="section2" class="section">Section 2</div>
<div id="section3" class="section">Section 3</div>
<script>
const sections = document.querySelectorAll('.section');
const navLinks = document.querySelectorAll('.nav a');
function highlightNav() {
let current = '';
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= sectionTop - sectionHeight / 3) {
current = section.getAttribute('id');
}
});
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href').substring(1) === current) {
link.classList.add('active');
}
});
}
window.addEventListener('scroll', highlightNav);
</script>
</body>
</html>
requestAnimationFrame
优化滚动事件的处理。function highlightNav() {
// 原有逻辑
}
let ticking = false;
window.addEventListener('scroll', () => {
if (!ticking) {
window.requestAnimationFrame(() => {
highlightNav();
ticking = false;
});
ticking = true;
}
});
href
属性是否正确对应。通过以上方法,可以有效实现并优化楼层点亮效果,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云