由于您没有添加html
部分代码并且也没有jsfiddle
提供,因此很难完全按照您的需要回答。以下是您可以用来了解可以在实际代码中应用的修改以获取颜色更改链接的代码
这是演示,但它不包含解释,所以请阅读下面 javascript 代码中的注释
html
<ul id="nav">
<li id="link1"><a href="#">Link 1</a></li>
<li id="link2"><a href="#">Link 2</a></li>
<li id="link3"><a href="#">Link 3</a></li>
<li id="link4"><a href="#">Link 4</a></li>
</ul>
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
css
*{
margin:0;
}
#nav {
position: fixed;
list-style-type: none;
}
#nav a{
text-decoration: none;
color: orange;
}
#a{
width: 100%;
height: 600px;
background: lightgreen
}
#b{
width: 100%;
height: 200px;
background: orange;
}
#c{
width: 100%;
height: 400px;
background: purple
}
脚本
var b=$('#b').offset();
var c=$('#c').offset();
$(window).scroll(function(){
/*The same colored region `(orange div with id="b")` is reached and we are still
inside that region not below it that is not in purple region, for this the if
condition block is used. This condition will also recolor the link when we
scroll towards top from purple (below) to orange (same colored) region */
if( $(window).scrollTop()+$('#nav').height()>=b.top+10 &&
$(window).scrollTop()+$('#nav').height()<c.top+10 )
{
$('#link4 a').css('color','green');
}
/*we scroll back from same colored region towards top that is from orange to
lightgreen region*/
else if($(window).scrollTop()<b.top+70)
{
$('#link4 a').css('color','orange');
}
/* we scroll below the same colored region that is links are to be recolored
with their original color when we scroll from orange to purple region*/
else if($(window).scrollTop()+$('#nav').height()>=c.top+10)
{
$('#link4 a').css('color','orange');
}
/*Same if,else if and else if for other three links*/
if( $(window).scrollTop()+$('#nav').height()>=b.top+30 &&
$(window).scrollTop()+$('#nav').height()<c.top+30 )
{
$('#link3 a').css('color','green');
}
else if($(window).scrollTop()<b.top+50)
{
$('#link3 a').css('color','orange');
}
else if($(window).scrollTop()+$('#nav').height()>=c.top+30)
{
$('#link3 a').css('color','orange');
}
if( $(window).scrollTop()+$('#nav').height()>=b.top+50 &&
$(window).scrollTop()+$('#nav').height()<c.top+50 )
{
$('#link2 a').css('color','green');
}
else if($(window).scrollTop()<b.top+30)
{
$('#link2 a').css('color','orange');
}
else if($(window).scrollTop()+$('#nav').height()>=c.top+50)
{
$('#link2 a').css('color','orange');
}
if ( $(window).scrollTop()+$('#nav').height()>=b.top+70 &&
$(window).scrollTop()+$('#nav').height()<c.top+70 )
{
$('#link1 a').css('color','green');
}
else if($(window).scrollTop()<b.top+10)
{
$('#link1 a').css('color','orange');
}
else if($(window).scrollTop()+$('#nav').height()>=c.top+70)
{
$('#link1 a').css('color','orange');
}
});
注意:-的位置ul#nav
是固定的,这就是为什么我们必须添加它的高度才能$(window).scrollTop()
获得窗口的确切滚动位置
注意:-每个链接的单独条件集仅在需要时用于更改链接的颜色,即仅当Link 4
处于橙色区域时,仅对仍处于浅绿色区域的链接应用绿色
如有疑问,请随时提出
编辑:粘贴图像(右键单击并在新选项卡中打开以查看完整大小)以回应解释10,30..
代码中数字重要性的评论