Goal:
prevent the yes
class being removed from an element if it isn't being added to another.
I have the following code:
jQuery(function($){
$(window).scroll(function() {
var position = $(this).scrollTop();
if ($('#services').length) {
$('section').each(function() {
var target = $(this).offset().top;
var id = $(this).attr('id');
//if statement goes here i think?
if (position >= target - 79) {
$('.menu-wrap > ul > li > a').removeClass('yes');
$('.menu-wrap > ul > li > a[href*="#' + id + '"]').addClass('yes');
}
});
};
});
})
I'd like to write a nested if
statement that will trigger position >= target
if one of the menu items links (<a href="#~"/>
) is the same as the id
of any of the section
elements on the page.
HTML as requested
<div class="menu-wrap">
<ul class="nav"><li><a href="#home"/></li><li><a href="second"/></li></ul>
</div>
<section id="home"></section>
<section id="an-id-that-isnt-in-the-menu"></section>
<section id="second"></section>
答案 0 :(得分:0)
您的if
声明应该是这样的:
var selector = ".menu-wrap > ul > li > a[href=#" + id + "]";
if ($(selector).length) {
用你的JS:
jQuery(function($){
$(window).scroll(function() {
var position = $(this).scrollTop();
if ($('#services').length) {
$('section').each(function() {
var target = $(this).offset().top;
var id = $(this).attr('id');
var selector = ".menu-wrap > ul > li > a[href=#" + id + "]";
if ($(selector).length > 0) {
if (position >= target - 79) {
$('.menu-wrap > ul > li > a').removeClass('yes');
$('.menu-wrap > ul > li > a[href*="#' + id + '"]').addClass('yes');
}
}
});
};
});
});