(1).左侧导航条固定效果是由如下代码实现的:
ul {
position: fixed;
height: 40px;
line-height: 40px;
top: 100px;
}
top值等于100px要特别注意一下,因为后面会用到。
(2).鼠标悬浮导航栏目实现变色效果是由如下代码实现的:
ul {
position: fixed;
height: 40px;
line-height: 40px;
top: 100px;
}
(3).$(function () {}),当文档结构完全加载完毕再去执行函数中的代码。
(4).$('li').on('click', function () {}),为li元素注册时间处理函数,当点击li元素的时候也能够实现导航效果。
(5).var index = $(this).index(),获取当前点击li元素的索引值。
(6).var scrollTo = $('.content').eq(index).offset().top,获取对应索引的div元素距离文档顶端的距离。
(7).$('body').animate({ scrollTop: scrollTo
}, 200),以动画方式设置body的scrollTop值,这样就会使对应索引的div块顶端到达窗口顶端。
(8).$(this).addClass('active').siblings().removeClass('active'),为当前元素添加名称为active的样式类,其他的li元素则删除它,于是就实现了当前li元素呈现绿色的效果。
(9).var barItemTops = [],声明一个数组,后面会用到。
(10).$('li').each(function (index, element) {
barItemTops.push($(this).position().top + 100);
}),获取每一个li元素的position().top值,再加上100,恰好是每一个li元素顶端,距离窗口顶端的尺寸。
(11).$(window).on('scroll', function () {}),为window注册scroll事件处理函数。
(12).var winScrollTop = $(this).scrollTop(),网页向上滚动的尺寸。
(13).$('.content').each(function (index, element) {}),遍历每一个div元素。
(14).var selfOffsetTop = $(this).offset().top,获取div元素距离文档顶部的距离。
(15).if (0 <= selfOffsetTop - winScrollTop && selfOffsetTop - winScrollTop < barItemTops[index]) {
$('li').eq(index).addClass('active').siblings().removeClass('active');
},selfOffsetTop - winScrollTop值就是div元素的顶端距离窗口顶端的尺寸。
也就是如果这个尺寸大0并且小于侧边栏导航对应的li元素顶端距离窗口顶端的距离,那么将设置对应li元素的相关样式。