我的问题是这个。我有一个固定的左侧导航栏,我必须根据其下面部分的背景来更改列表字体的颜色。代码类似于fiddle。因此,如果该部分为黑色且在链接下方,则看不到该文本。我必须根据其下一节的背景更改每个列表,以便使其可读。
html
<div class="content">
<div id="left_side">
<div id="static_menu" class="">
<div id="main_navigation" class="">
<ul class="menu mainLeft" id="mymenu">
<li><a href="#section1">Nav list 1</a></li>
<li><a href="#section2">Nav list 2</a></li>
<li><a href="#section3">Nav list 3</a></li>
<li><a href="#section4">Nav list 4</a></li>
<li><a href="#section5">Nav list 5</a></li>
</ul>
</div>
</div>
</div>
<div id="wrapper">
<div class="section" id="section1">section1</div>
<div class="section" id="section2">section2</div>
<div class="section" id="section3">section3</div>
<div class="section" id="section4">section4</div>
<div class="section" id="section5">section5</div>
</div>
</div>
的CSS
.content{
position:relative;
}
#left_side
{
position:fixed;
left: 20px;
right: 20px;
z-index:999;
}
.mainLeft
{
list-style-type:none;
margin-left:0px;
padding-left:0px;
}
.mainLeft li
{
padding:5px 0;
}
.mainLeft li a
{
color:#000;
margin-bottom:5px;
}
#wrapper
{
position:relative;
}
.section
{
width: 100%;
text-align:center;
padding:150px 0;
border:1px solid #666;
}
#section1
{
background: #fff;
}
#section2
{
background: #000;
color:#fff;
}
#section3
{
background: #fff;
}
#section4
{
background: #000;
color:#fff;
}
#section5
{
background: #fff;
}
Fiddel
最佳答案
要执行您想要的操作,可以使用jquery做到这一点:
working fiddle
var _li, _sections;
$(function() {
_li = $("#mymenu").find("li");
_sections = $("#wrapper").find(".section");
$(window).on('scroll', liBgs);
});
function liBgs() {
for (var i = 0; i < _li.length ; i++) {
var _litop = _li.eq(i).offset().top;
for (var j = 0; j < _sections.length; j++) {
var $s = _sections.eq(j),
_sectop = $s.offset().top,
_secbottom = $s.offset().top+$s.height()-20;
if (_litop > _sectop && _litop > _secbottom) {
var _color = rgb2hex($s.css('background-color'));
_li.eq(i).find('a').css('color', (_color=="#ffffff") ? "#000000" : "#ffffff");
}
}
}
}
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
注意:rgb2hex()函数来自以下问题:How to get hex color value rather than RGB value?
该代码的作用:
我基本上是比较菜单li的位置与各部分的位置,检查下是什么
每次滚动时,每个li都结束了。.我不确定这是否非常有效,但是对于小规模的事情来说也可以。.如果有人知道如何提高效率,我将很高兴学习。