我正在尝试使用jQuery航点更新单页网站的导航。
我想根据视图中的当前部分更新导航。使用导航链接时,它可以正常工作。我的问题是当你尝试滚动到当前部分上方的一个部分时,活动锚点应该在下面的位置。
请参阅我的Demo。
的jQuery
$(document).ready(function(){
$('section').waypoint(function(direction) {
thisId = $(this).attr('id');
$('ul li').each(function(){
var secondaryID = $(this).attr('class');
if ( secondaryID == thisId )
{
$('ul li').removeClass('active');
$(this).addClass('active');
}
});
},{offset: '0'});
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
return false;
}
}
});
HTML
<ul>
<li class="test"><a href="#test"></a></li>
<li class="test2"><a href="#test2"></a></li>
<li class="test3"><a href="#test3"></a></li>
<li class="test4"><a href="#test4"></a></li>
<li class="test5"><a href="#test5"></a></li>
</ul>
<section id="test"></section>
<section id="test2"></section>
<section id="test3"></section>
<section id="test4"></section>
<section id="test5"></section>
更新
我使用具有不同偏移的两个航路点功能来实现这一点,但这显然不是最佳解决方案。
我试图找到一种在同一个函数中指定偏移的方法(取决于方向),我使用一个变量作为偏移量,值为(1&amp; -1),但遗憾的是它只使用+1。
答案 0 :(得分:3)
$(document).ready(function(){
$('section').waypoint(function(direction) {
var me = $(this); //added
thisId = $(this).attr('id');
$('ul li').each(function(){
var secondaryID = $(this).attr('class');
if ( secondaryID == thisId )
{
$('ul li').removeClass('active');
//added
if(direction==='up'){
me = $(this).prev();
}
//added
if(!me.length){
me = $(this);
}
$(this).addClass('active');
}
});
},{offset: '0'});
});
<强> UPD 强> 好的,this example怎么样:
这个想法是:
1)当我们点击N部分顶部边框时,向下滚动,表示活动部分变为部分N + 1.
2)当我们点击N部分顶部边框时,滚动顶部,意味着部分N变为活动状态。
PS。对不起我的英文
的Javascript
$(document).ready(function(){
$('section').waypoint(function(direction) {
var activeSection = $(this);
if(direction === 'down'){
activeSection = $(this).next();
}
//activeSection = $(this);
var sectionId = activeSection.attr('id');
$('ul li').removeClass('active');
$('ul li.' + sectionId).addClass('active');
console.log(activeSection);
});
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - (target.height() / 5)
}, 500);
return false;
}
}
});