在网上找了好久的关于导航栏锚点定位,和滚动定位导航栏。结果发现不是不能用,就是定位不准确,没有使用防抖。
也看到了一个大神写的原生js,但是实际开发可能用不到,我就自己研究了一下,把代码整理了一下,分享给大家,如有不足,不吝赐教。
css部分
<style>
.active {
background: red;
}
</style>
html部分:
<body>
<div class="outheight" style="height: 5000px;">
<div class="nav" style="height: 350px; width: 200px; position: fixed; top: 200px;">
<div class="nav_list" style="height: 100px;margin-bottom: 10px; border: solid 1px black;"></div>
<div class="nav_list" style="height: 100px;margin-bottom: 10px; border: solid 1px black;"></div>
<div class="nav_list" style="height: 100px;margin-bottom: 10px; border: solid 1px black;"></div>
</div>
<div class="contair" style="width: 400px;margin-left: 400px;">
<div class="hhh" style="height:300px"></div>
<div class="list" style="height: 500px;border: solid 1px red; margin-bottom: 50px;margin-top: 100px;">
</div>
<div class="list" style="height: 500px;border: solid 1px red; margin-bottom: 50px;">
</div>
<div class="list last_list" style="height: 500px;border: solid 1px red; margin-bottom: 50px;">
</div>
</div>
</div>
</body>
js部分 先引用jquery库,我这里直接引用了百度的jqeury cdn
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
//我们要用到的变量
var sectionArray = []
//设置导航栏的初始值
var nav_list_index = null;
//一半屏幕的高度
var halfHeight = $(window).height() / 2;
//通过循环获取每个锚点的高度,放入数组中
//有时候会因为页面加载慢的原因,获取不到准确的偏移量,
//因此,我们可以使用$(document).ready(function(){})方法来解决此类问题。
$('.list').each(function() {
sectionArray.push($(this).offset().top)
})
function scorllShow() {
//卷去的高度
var loseHeight = $(window).scrollTop();
//需要判断的高度 = 卷去的高度 + 一半屏幕的高度 (这里一半高度可不要,我主要是想实现一半的情况)
var allHeight = loseHeight + halfHeight;
var height = $(".list:last", parent.document).offset().top
var heightBody = $(document).scrollTop();
if (heightBody >= height + 200) {
$('.nav').hide();
} else {
$('.nav').show();
}
// 这里的m代表当前元素的索引值 n表示当前元素
$('.list').each(function(m, n) {
//因为高度一般会有0.几的误差,如 222.199999; 可能差0.111 到223,
//所以在比较的时候,可以在后面的高度写个20左右的偏移量
if (allHeight >= sectionArray[m] - 20) {
//条件成立,则给对应索引的导航栏增加样式 ,两种增加的都可以
// $('.nav_list').eq(m).addClass("active").siblings().removeClass("active");
$(".nav_list").removeClass('active');
$('.nav_list').eq(m).addClass("active")
return
}
})
}
//防抖的函数
function debounce(fn, delay) {
let timer = null
return function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(fn, delay);
}
}
//调用防抖的方法
window.onscroll = debounce(scorllShow, 50);
$(".nav .nav_list").click(function() {
nav_list_index = $(this).index();
//先去样式,再添加样式
$(".nav_list").removeClass('active');
$(this).addClass('active')
$('body, html').animate({
scrollTop: sectionArray[nav_list_index] - halfHeight
}, 500);
})
</script>
忙活了一整天,希望大家可以评论,交流。