需要做个手机站,顶端有导航栏,点击导航栏页面滑到相应位置,并且滑动页面,导航栏也随之变化。由于不大会js,只能网上找了些代码,但是都不完全适用,就自己改造了一番,写的比较粗糙,但是对初学者来说,算是比较好懂
$(function () {
var cont1 = $("#yswy").offset().top - 100;//获取模块距页面顶部的距离,由于有固定定位的导航栏,所以减100var cont2 = $("#ymcz").offset().top - 100;
var cont3 = $("#yyew").offset().top - 100;
var cont4 = $("#lcyy").offset().top - 100;
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲but1').click(fu…(‘html,body’).animate({scrollTop:$(’#yswy’).offset().top - 91}, 400);});//点击滑动到模块位置 由于有导航栏减91
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲but2').click(fu…(‘html,body’).animate({scrollTop:$(’#ymcz’).offset().top - 91}, 400);});
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲but3').click(fu…(‘html,body’).animate({scrollTop:$(’#yyew’).offset().top - 91}, 400);});
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲but4').click(fu…(‘html,body’).animate({scrollTop:$(’#lcyy’).offset().top - 91}, 400);});
window.onscroll = function(){
var t = document.documentElement.scrollTop || document.body.scrollTop; //获取距离页面顶部的距离if( t >= cont1 && t <= cont2) { //到顶部的距离介于两者之间时$("#but1 span").addClass("active");//添加class,改变对应导航栏颜色} else {
$("#but1 span").removeClass(“active”);
}
if ( t >= cont2 && t <= cont3) {
$("#but2 span").addClass(“active”);
} else {
$("#but2 span").removeClass(“active”);
}
if ( t >= cont3 && t <= cont4) {
$("#but3 span").addClass(“active”);
} else {
$("#but3 span").removeClass(“active”);
}
if ( t >= cont4 ) {
$("#but4 span").addClass(“active”);
} else {
$("#but4 span").removeClass(“active”);
}
}
})
全部文件:链接:/s/1tH3580pwea5YqUMlCHYiRw 密码:t7gf