我是新来的,只是开始学习javascript / jQuery,我编写了一些代码,但我认为它不是有效的代码,因为时间太长,有点重复同样的事情,你们也许可以制作一个更简单的代码版本这个呢?谢谢。
在这里,我附上html图片:
var sections = $('.section-page'),
sp = $('.sp'),
sp2 = $('.sp2'),
sp3 = $('.sp3');
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').parent().closest('li').removeClass('current');
nav.find('a[href="#'+$(this).attr('id')+'"]').parent().closest('li').addClass('current');
}
});
sp.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').parent().closest('li').removeClass('current');
$('#cssmenu > ul > li:nth-child(7)').addClass('current');
}
});
sp2.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').parent().closest('li').removeClass('current');
$('#cssmenu > ul > li:nth-child(6)').addClass('current');
}
});
sp3.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').parent().closest('li').removeClass('current');
$('#cssmenu > ul > li:nth-child(3)').addClass('current');
}
});
});
最佳答案
您可以为重复创建4次的代码创建一个函数-可以通过将参数传递给该函数来覆盖其中的一些变化:
var sections = $('.section-page'),
sp = $('.sp'),
sp2 = $('.sp2'),
sp3 = $('.sp3');
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
function setCurrent(elem, child) {
elem.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').parent().closest('li').removeClass('current');
var li = child !== undefined
? $('#cssmenu > ul > li:nth-child(' + child + ')')
: nav.find('a[href="#'+$(this).attr('id')+'"]').parent().closest('li');
li.addClass('current');
}
});
}
setCurrent(sections); // second argument not passed => undefined child
setCurrent(sp, 7);
setCurrent(sp2, 6);
setCurrent(sp3, 3);
});