我希望使用jquery添加一个类别的“选定”,无论是点击导航项目,以及滚动通过该部分的div。
到目前为止,我已经在点击导航项目时添加了类,但我不确定如何在滚动经过每个部分div时整齐地添加相同的效果。
以下是我的脚本,用于在单击时添加类(这非常简单和标准):
$('#fixednav li').click(function(){
$('#fixednav li').removeClass("selected");
$(this).addClass("selected");
});当用户单击固定菜单中的项目时,...It all效果很好。但是,当用户在没有使用固定菜单的情况下向下滚动页面时,如何添加所选的类?每个部分都有一个div id,所以我认为可以很容易地添加一些东西,以便在滚动过div id时添加类。
稍微向下滚动一点可以看到固定的导航弹出...
发布于 2014-04-11 00:18:14
发布于 2014-04-11 00:24:02
检查这是否对fiddle有帮助
这是使用的js,检查html和css的小提琴。
var hei = $("#header").height();
$(window).scroll(function(){
if($(window).scrollTop() > hei){
$("#header").addClass('fixed');
$('.body-wrapper').css('margin-top',hei);
}else{
$("#header").removeClass('fixed');
$('.body-wrapper').css('margin-top','0');
}
});
$("#header li a").on('click', function(event){
event.preventDefault();
var header_height = $("#header").height();
var target = $(this).attr('href');
$('html, body').animate({
scrollTop: $(target).offset().top-header_height
}, 1000);
});
var aChildren = $("#header li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top-hei-30; // get the offset of the div from the top of page
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-active");
}
}
});https://stackoverflow.com/questions/22993421
复制相似问题