我想在滚动时更改ul样式并使用jQuery到达div,解释下来.
CSS:
#menu {
background-color:#ccc;
position:fixed;
width:100%;
}
.menutext {
padding:25 40 30 !important;
display:inline-block;
}
.menutext2 {
padding:25 40 0 !important;
display:inline-block;
color:red;
}
.alldivs {
width:300px;
height:200px;
background-color:a9a9a9;
}
HTML代码:
<div id="menu">
<div class="menutext">Change the style of me to .mebutext2 on arriving to DIV1</div>
<div class="menutext">Change the style of me to .mebutext2 on arriving to DIV2</div>
<div class="menutext">Change the style of me to .mebutext2 on arriving to DIV3</div>
</div>
<br><br><br>
<div class="alldivs"><div id="DIV1">DIV1</div></div>
<br><br><br><br>
<div class="alldivs"><div id="DIV2">DIV2</div></div>
<br><br><br><br>
<div class="alldivs"><div id="DIV3">DIV3</div></div>
<br><br><br><br>
我想在滚动时将类“menutext”更改为class“menutext2”并到达div的顶部(第一次ul的类从menutext1更改为menutext2,到达具有id DIV1的div,第二次ul的类更改从menytext1到menutext2到达具有id DIV2的div并且第一个ul的类返回menutext1 AS IT WAS等等.
解决方法
这应该只使用jQuery做你要问的事情:
$(document).scroll(function(e) {
var detectrange = 50; //how close to the top of the screen does it need to get
var scrolltop = $(window).scrollTop() + detectrange;
$('.alldivs').each(function(i,el){
if (scrolltop > $(el).offset().top) {
$('.'+el.id).removeClass('menutext').addClass('menutext2');
}
});
});
请注意,要使其工作,我必须在div1,div2,div3等上应用alldivs类,并提供与其ID对应的菜单项类.
演示这个jsfiddle:http://jsfiddle.net/ss7YF/
编辑如果你只想要最近的一个突出显示(对于我猜的固定菜单?)使用:
$(document).scroll(function(e) {
var scrolltop = $(window).scrollTop();
var mindist = 1000;
var closest = '';
$('.alldivs').each(function(i,el){
var thisdist = Math.abs(scrolltop - $(el).offset().top);
if (thisdist < mindist) {
closest = el.id;
mindist = thisdist;
}
});
if (closest != '') {
$('.menutext2').toggleClass('menutext menutext2');
$('.'+closest).toggleClass('menutext menutext2');
}
});
jsfiddle:http://jsfiddle.net/ss7YF/1/