This should do what you're asking, using only jQuery:
$(document).scroll(function(e) {
var detectrange = 50; //how close to the top of the screen does it need to get
var scrolltop = $(window).scrollTop() + detectrange;
$('.alldivs').each(function(i, el){
if (scrolltop > $(el).offset().top) {
$('.'+el.id).removeClass('menutext').addClass('menutext2');
}
});
});
Note that to make it work I had to apply the alldivs
class on your div1
, div2
, div3
, etc. and give the menu items classes corresponding to their IDs.
Demo in this jsFiddle: http://jsfiddle.net/ss7YF/
EDIT If you want only the closest one to be highlighted (for a fixed menu I'm guessing?) use this:
$(document).scroll(function(e) {
var scrolltop = $(window).scrollTop();
var mindist = 1000;
var closest = '';
$('.alldivs').each(function(i, el){
var thisdist = Math.abs(scrolltop - $(el).offset().top);
if (thisdist < mindist) {
closest = el.id;
mindist = thisdist;
}
});
if (closest != '') {
$('.menutext2').toggleClass('menutext menutext2');
$('.'+closest).toggleClass('menutext menutext2');
}
});
jsFiddle: http://jsfiddle.net/ss7YF/1/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…