我正在创建我的第一个单页网站。
这是一个小伙伴:http://jsfiddle.net/dgfhjxLt/
当您滚动页面时,链接颜色应该更改以显示他们在该页面上的用户,到目前为止这个工作正常,问题在于第一个div。
当你第一次进入网站时,第一个链接应该显示为活动,即文本应该是蓝色,这不会发生,直到你先滚动一点,然后它才能正常工作。
被困了一个小时,乖乖这是一个简单的解决办法吗?
这里是jquery:
jQuery(document).ready(function($) {
var offsetHeader = 60;
$('.scroll').click(function(){
var $target = $($(this).attr('href'));
$(this).parent().addClass('active');
$('body').stop().scrollTo( $target , 800, {'axis':'y', offset: -offsetHeader});
return false;
});
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $("nav 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-60; // 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("active");
} else {
$("a[href='" + theID + "']").removeClass("active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("nav li:last-child a").addClass("nav-active");
}
}
});
});
答案 0 :(得分:2)
您的jQuery在锚点上使用active
类,但您在第一个元素上使用li
上的活动类只需将其移动到锚标记,如下所示:
<li><a class="scroll active" href="#test1">test1</a></li>
<强> DEMO 强>