我有一个带有导航菜单的单页网站position:fixed
在页面顶部。
当我单击导航菜单中的链接时,页面会使用以下 JQuery 滚动到相应的部分:
$('a[href^="#"]').live('click',function(event){
event.preventDefault();
var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
$('html, body').animate({scrollTop:target_offset}, 1200, 'easeOutExpo');
});
我希望发生的是当我手动滚动页面时$(window).scroll(function(){...});
,与导航菜单下经过的部分相关#navi-container
,导航链接突出显示使用.addClass('activeNav');
查看我几天前偶然发现的这个 jsfiddle,我相信这正是您正在寻找的:http://jsfiddle.net/x3V6Y/ http://jsfiddle.net/x3V6Y/
$(function(){
var sections = {},
_height = $(window).height(),
i = 0;
// Grab positions of our sections
$('.section').each(function(){
sections[this.name] = $(this).offset().top;
});
$(document).scroll(function(){
var $this = $(this),
pos = $this.scrollTop(),
$parent = {};
for(i in sections){
$parent = $('[name="' + i + '"]').parent();
//you now have a reference to a jQuery object that is the parent of this section
if(sections[i] > pos && sections[i] < pos + _height){
$('a').removeClass('active');
$('#nav_' + i).addClass('active');
}
}
});
});
我想指出的是,如果你最终使用这个,你会重新考虑for(i in sections)
循环,因为它对性能造成很大影响。如果可以的话,使用这种循环是一个好主意:
for (var i = 0, len = sections.length; i < len; i++) {
//...
}
...但这需要重新考虑如何存储节元素的偏移量,因为这种类型的循环需要一个数组而不是一个对象(对象可以工作,但它必须是零索引的,并且所有索引都有为整数)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)