!function(win,doc){
// 快速导航
var $dir = $('.art-aside-dir');
// 需要快速导航定位到的项
var $hd = $('.art-sec .hd');
// 离顶部距离
var spaceTop = 50;
// 创建导航html
$hd.each(function(i){
var $t = $(this);
$t.attr('id','art-h-' + i);
$dir.append('<li data-id="art-h-' + i + '">' + $t.text() + '</li>')
});
var dirTop = 0;
// 存储手动点击的导航项
var hand;
$(win).scroll(function(e) {
var winTop = $(win).scrollTop();
var $currH2;
if ( winTop > dirTop ) {
$dir.css('top',winTop);
} else {
$dir.css('top',dirTop);
}
$hd.each(function(i){
// 如果此标题大于视口上边时
// 如果当前标题是第一个标题就返回第一个并退出,否则返回它之前的一个
if ( $(this).offset().top - spaceTop > winTop ) {
$currH2 = i == 0 ? $hd.eq(0) : $hd.eq( i - 1 );
return false;
} else {
// 当视口上边已经大于最后一个标题时就返回最后一个标题
$currH2 = $hd.filter(':last')
}
});
var winH = $(win).height();
var docH = $(doc).height();
// 存在手动点击导航项时
if ( hand ) {
$dir.children().removeClass('on').filter('[data-id=' + hand.attr('id') + ']').addClass('on');
// 手动点击导航项滚动到期望位置误差值小于1时就假设已到达期望位置,停止滚动
var scrolled = winTop - (hand.offset().top - spaceTop);
// 到了页尾或到了点击项位置
if ( winTop + winH == docH || (scrolled < 1 && scrolled > -1) ) {
$('body,html').stop(true);
// 删除暂存的点击项
hand = undefined;
}
// 不存在手动点击项时
} else {
// 到页尾是直接设置最后一个导航项
if ( winTop + winH == docH ) {
$dir.children().removeClass('on').filter(':last').addClass('on');
} else {
// 设置当前滚动到的项
$dir.children().removeClass('on').filter('[data-id=' + $currH2.attr('id') + ']').addClass('on');
}
}
$dir.show();
});
$dir.children().click(function(){
hand = $hd.filter('#' + $(this).attr('data-id'));
// 防止项的高度太短,不触发滚动时,当前点击的项没有加上当前项class
$dir.children().removeClass('on').filter('[data-id=' + hand.attr('id') + ']').addClass('on');
$('body,html').stop(true).animate({'scrollTop':hand.offset().top - spaceTop},'fast');
});
}(window,document)
目录导航
最新推荐文章于 2022-05-26 17:22:19 发布