这是 JSFiddle 链接: http://jsfiddle.net/asif097/HHEqx/
你好,
在上面的链接中,您会发现单击链接时,active
类将添加到 ('.nav-inner a')
,同时页面也会滚动。 (更多理解见代码):
$(document).ready(function() {
$('html, body').animate({
scrollTop: $(".target1").offset().top
}, 1000);
$('#link1').click(function() {
$('html, body').animate({
scrollTop: $(".target1").offset().top
}, 1000);
$('.nav-inner a').removeClass("active");
$(this).addClass("active");
});
$('#link2').click(function() {
$('html, body').animate({
scrollTop: $(".target2").offset().top,
}, 1000);
$('.nav-inner a').removeClass("active");
$(this).addClass("active");
});
$('#link3').click(function() {
$('html, body').animate({
scrollTop: $(".target3").offset().top
}, 1000);
$('.nav-inner a').removeClass("active");
$(this).addClass("active");
});
});
现在 当我手动滚动 addClass() 以相同的方式运行时,我希望发生这种情况。试过这个:
$('html, body').scroll(function ()
{
if(($('html, body').scrollTop())<1000)
{
$(".nav-inner a").removeClass('active');
$(".nav-inner a:nth-child(1)").addClass('active');
}
else if(($('html, body').scrollTop())<2000)
{
$(".nav-inner a").removeClass('active');
$(".nav-inner a:nth-child(2)").addClass('active');
}
else
{
$(".nav-inner a").removeClass('active');
$(".nav-inner a:nth-child(3)").addClass('active');
}
});
但是,不起作用。任何人都可以修复我的代码吗? (需要解释)
谢谢。
最佳答案
$(window).scroll(function (){
var scrll = $(this).scrollTop();
if(scrll < 1000)
{
$(".nav-inner a").removeClass('active');
$(".nav-inner a:nth-child(1)").addClass('active');
}
else if(scrll < 2000)
{
$(".nav-inner a").removeClass('active');
$(".nav-inner a:nth-child(2)").addClass('active');
}
else
{
$(".nav-inner a").removeClass('active');
$(".nav-inner a:nth-child(3)").addClass('active');
}
});
关于jquery - 手动滚动添加类在这里不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14908908/