这个练习的关键点在于理解元素的尺寸与位置。
一、效果
二、具体代码
<style>
*{
margin: 0;
padding: 0;
text-decoration: none;
}
header,footer{
width: 800px;
height: 100px;
background-color: blueviolet;
margin: 0 auto;
}
.head{
width: 100%;
height: 60px;
background-color: cornflowerblue;
position: fixed;
top: -60px;
left: 0;
transition: all 1s;
}
section{
width: 800px;
height: auto;
margin: 0 auto;
}
.box{
width: 800px;
height: 400px;
background-color: darkcyan;
margin: 30px 0;
font-size: 30px;
line-height: 400px;
text-align: center;
}
.list{
width: 100px;
height: 180px;
position: fixed;
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
display: none;
}
.list li{
width: 100px;
height: 30px;
border: 1px solid #000;
box-sizing: border-box;
line-height: 30px;
text-align: center;
}
.list .active{
background-color: #ff6700;
color: #fff;
}
</style>
<body>
<header></header>
<div class="head"></div>
<section>
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
</section>
<ul class="list">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<footer></footer>
</body>
<script>
window.onload=function(){
var head=document.querySelector(".head");
var list=document.querySelector(".list");
var boxs=document.querySelectorAll(".box");
var lis=document.querySelectorAll(".list li");
//各楼层的高,点击事件
var arr=[];
for(let i=0;i<boxs.length;i++){
arr.push(boxs[i].offsetTop);
lis[i].onclick=function(){
for(var j=0;j<boxs.length;j++){
lis[j].classList.remove("active");
}
document.documentElement.scrollTop=arr[i];
lis[i].classList.add("active");
}
}
//滚动监听
window.onscroll=function(){
var a=document.documentElement.scrollTop;
if(a>=100){
head.style.top="0";
list.style.display="block";
}else{
head.style.top="-60px";
list.style.display="none";
}
//自动点亮
for(var i=0;i<boxs.length;i++){
if(a>=(arr[i]-200)){
for(var j=0;j<boxs.length;j++){
lis[j].classList.remove("active");
}
lis[i].classList.add("active");
}
}
}
}
</script>
这个效果比较简单,但在一些项目中会和其他的一些效果联用,像苏宁的网站就有这个效果。还是比较重要的,每个项目中可能不会一样,但主要思想相同。