- 适用多个菜单,根据class获取高度
- 可滑动到指定位置选中指定菜单
- 样式有点丑,实在不想写,哈哈,大家自行优化
- 首先获取所有内容区域高度并且前一个元素的高度加后一个元素的高度形成一个数组
- 监听滚动元素区域
$('.scroll-content-box').scroll
- 判断数组里的高度对应哪个菜单
- 点击菜单更加下标页面滑动相应距离
- $().animate()加点动画
话不多说,上代码!
<div class="content">
<div class="scroll-menu-box">
<div class="scroll-menu-item" id="active" name="0">第一个</div>
<div class="scroll-menu-item" name="1">第二个</div>
<div class="scroll-menu-item" name="2">第三个</div>
<div class="scroll-menu-item" name="3">第四个</div>
</div>
<div class="scroll-content-box">
<div class="scroll-card-box">第一个</div>
<div class="scroll-card-box">第二个</div>
<div class="scroll-card-box">第三个</div>
<div class="scroll-card-box" style="height: 400px">第四个</div>
</div>
</div>
let clientHeightList = []
let clientHeightCountList = []
$('.scroll-card-box').each(function(e){
let that = $(this)
let clientHeight = that.height()
clientHeightList.push(clientHeight)
})
let countHeiht = 0
for (let idx = 0; idx < clientHeightList.length; idx++) {
if(idx == 0){
clientHeightCountList.push(0)
}else{
countHeiht = countHeiht + clientHeightList[idx]
clientHeightCountList.push(countHeiht)
}
}
$('.scroll-content-box').scroll((e)=>{
let scrollTop = e.currentTarget.scrollTop
clientHeightCountList.forEach((val,index) => {
if(index == clientHeightCountList.length-1){
if(scrollTop > clientHeightCountList[index] - 100){
addClass(index)
}
}else{
console.log(val)
if(scrollTop >= val && scrollTop < clientHeightCountList[index+1]-50){
addClass(index)
}
}
});
})
function addClass(index){
$('.scroll-menu-item').removeAttr('id')
$('.scroll-card-box').each(function(e){
let that = $(this)
let clientHeight = that.height()
$('.scroll-menu-item')[index].setAttribute('id','active')
})
}
$('.scroll-menu-item').click(function(e){
let that = $(this)
$('.scroll-content-box').animate({
scrollTop: clientHeightCountList[that.attr('name')]
}, 300)
})
.content{
width: 100%;
display: flex;
}
.scroll-menu-box{
width: 200px;
height: 300px;
}
.scroll-menu-item{
height: 50px;
background-color: #e8e8e8;
margin-bottom: 50px;
}
.scroll-content-box{
height: 500px;
flex: 1;
overflow-y: scroll;
}
.scroll-content-box .scroll-card-box{
margin: 0;
height: 500px;
background-color: pink;
}
#active{
background-color: aqua;
}