我在这里有一个持久的黄色菜单:http://jsfiddle.net/KCb5z/11/
正如您所见,它仍然在页面上。我想要实现的是在用户滚动到该部分后将活动阶段放在菜单项上(即黄色菜单位于当前部分的顶部)
似乎有很多不同的尝试方法,但我真的不知道如何开始。 Bootstrap在这里(当你向下滚动时)http://getbootstrap.com/javascript/用一些名为scrollspy的东西来做它,但是对于那么简单的东西来说代码看起来很大:
// Cache selectors
var lastId,
topMenu = $("#top-menu"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#"+id+"]").parent().addClass("active");
}
});
答案 0 :(得分:1)
你去了
$(function () {
var $select = $('#select');
var $window = $(window);
var isFixed = false;
var init = $select.length ? $select.offset().top : 0;
$window.scroll(function () {
var currentScrollTop = $window.scrollTop();
if (currentScrollTop > init && isFixed === false) {
isFixed = true;
$select.css({
top: 0,
position: 'fixed'
});
$('body').css('padding-top', $select.height());
} else if (currentScrollTop <= init && isFixed === true) {
isFixed = false;
$select.css('position', 'relative');
$('body').css('padding-top', 0);
}
//active state in menu
$('.section').each(function(){
var eleDistance = $(this).offset().top;
if (currentScrollTop >= eleDistance) {
var makeActive = $(this).attr('id');
$('#select a').removeClass('active');
$('#select a.' + makeActive).addClass('active');
}
});
});
$(".nav").click(function (e) {
e.preventDefault();
var divId = $(this).attr('href');
$('body').animate({
scrollTop: $(divId).offset().top - $select.height()
}, 500);
});
});