我在处理平滑滚动以及主导航上的活动状态的脚本时遇到了一些问题。插件:http ://tinyurl.com/amz4kob
请注意,导航栏是固定的,因此实际上没有高度。
我有两个似乎无法克服的问题:
- 在页面加载时,活动状态将应用于联系链接。如果向下滚动 1px,则活动状态会正确应用于主链接。
- 我一生都无法弄清楚如何修改脚本以关注具有特定 ID 的元素中的锚点?即我只希望此脚本将活动状态应用于标记内的元素。
任何帮助将不胜感激。
@rrfive
为了让生活更轻松,这里是注释脚本:
$(document).ready(function() {
//Get Sections top position
function getTargetTop(elem){
//gets the id of the section header
//from the navigation's href e.g. ("#html")
var id = elem.attr("href");
//Height of the navigation
var offset = 0;
//Gets the distance from the top and subtracts the height of the nav.
return $(id).offset().top - offset;
}
//Smooth scroll when user click link that starts with #
$('a[href^="#"]').click(function(event) {
//gets the distance from the top of the section refenced in the href.
var target = getTargetTop($(this));
//scrolls to that section.
$('html, body').animate({scrollTop:target}, 500);
//prevent the browser from jumping down to section.
event.preventDefault();
});
//Pulling sections from main nav.
var sections = $('a[href^="#"]');
// Go through each section to see if it's at the top.
// if it is add an active class
function checkSectionSelected(scrolledTo){
//How close the top has to be to the section.
var threshold = 54;
var i;
for (i = 0; i < sections.length; i++) {
//get next nav item
var section = $(sections[i]);
//get the distance from top
var target = getTargetTop(section);
//Check if section is at the top of the page.
if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
sections.removeClass("active");
section.addClass("active");
}
};
}
//Check if page is already scrolled to a section.
checkSectionSelected($(window).scrollTop());
$(window).scroll(function(e){
checkSectionSelected($(window).scrollTop())
});
});