效果图如下
html结构
<!-- 内容 -->
<div class="box">
<div class="red"></div>
<p>频道广场</p>
<div class="blue"></div>
<p>为你推荐</p>
<div class="green"></div>
</div>
<!-- 侧边导航栏 -->
<div class="nav">
<div>京东秒杀</div>
<div>频道广场</div>
<div>为你推荐</div>
<div>返回顶部</div>
</div>
css样式
html, body {
-webkit-scroll-behavior: smooth; /* Chrome, Safari, and Opera */
-moz-scroll-behavior: smooth; /* Firefox */
-ms-scroll-behavior: smooth; /* Internet Explorer/Edge */
scroll-behavior: smooth; /* Standard syntax */
}
.box{
margin: 100px auto;
width: 800px;
background-color: #eee;
}
.red{
width: 800px;
height: 300px;
background-color: red;
}
.blue{
width: 800px;
height: 1000px;
background-color: blue;
}
.green{
width: 800px;
height: 6000px;
background-color: green;
}
p{
width: 800px;
height: 100px;
line-height: 100px;
text-align: center;
font-size: 30px;
font-weight: 700;
}
.nav{
position: fixed;
top: 80px;
right: 200px;
width: 50px;
height: 200px;
border: 1px solid #ccc;
border-bottom: 0;
}
.nav div{
width: 50px;
height: 50px;
font-size: 13px;
line-height: 15px;
padding: 10px;
box-sizing: border-box;
color: #666;
border-bottom: 1px solid #ccc;
transition: 1s;
}
.nav .active{
font-weight: 500;
color: red;
}
js代码
var height = 0 //存储获取的页面滚动高度
var nav = document.querySelectorAll(".nav div") //获取侧边栏内容
window.addEventListener("scroll",function() { // 实时获取页面滚动高度,达到某一位置时,使该部分内容高亮
height=window.scrollY
if(height>=100&&height<400){
nav[0].classList.add("active")
nav[1].classList.remove("active")
nav[2].classList.remove("active")
}else if(height<1500&&height>=400){
nav[1].classList.add("active")
nav[0].classList.remove("active")
nav[2].classList.remove("active")
}else if(height>=1500){
nav[2].classList.add("active")
nav[1].classList.remove("active")
nav[0].classList.remove("active")
}else{
nav[1].classList.remove("active")
nav[0].classList.remove("active")
nav[2].classList.remove("active")
}
})
// 点击时跳转到指定位置,过渡效果由css控制
nav[0].onclick = function(){
window.scrollTo(0,100)
}
nav[1].onclick = function(){
window.scrollTo(0,400)
}
nav[2].onclick = function(){
window.scrollTo(0,1500)
}
nav[3].onclick = function(){
window.scrollTo(0,0)
}
核心代码:
html, body {
-webkit-scroll-behavior: smooth; /* Chrome, Safari, and Opera */
-moz-scroll-behavior: smooth; /* Firefox */
-ms-scroll-behavior: smooth; /* Internet Explorer/Edge */
scroll-behavior: smooth; /* Standard syntax */
}
CSS中的scroll-behavior属性用于控制元素如何滚动。当使用值“smooth”时,滚动行为将平滑而不是突然地滚动。这个属性可以应用于包括窗口和元素滚动和平移等方面中的任何滚动。当它应用于一个元素时,此元素将在滚动的过程中呈现一种平滑效果,可以有效地提高用户的滚动体验。需要注意的是,这个属性目前只被一些最新的浏览器版本支持,不过可以通过添加前缀来使用。
scroll-behavior属性还可以取其他的值,包括auto和initial。其中,auto是scroll-behavior属性的默认值,它表示浏览器会使用它默认的滚动方式进行滚动,而不会使用任何自定义的滚动行为。初始值initial则表示将scroll-behavior属性设置回它的默认值auto。另外,一些浏览器还支持另外两个特定的值——snap和smooth。snap表示滚动行为将根据指定的范围(通常是元素的边缘)进行捕捉,并进行快速的滚动到捕捉点。smooth已经在之前提到过了,表示滚动行为将平滑地滚动。