我有一个单页网站,之前它有 3 个不同的页面,导航栏到当前页面的链接变成了“id="selected”
#selected {
background-color:white;
color: #645406;
cursor: default;
}
当您在该页面上时。 现在有点困难,因为链接就像 anchor 链接一样工作。 我需要一个脚本来检测用户滚动的位置,并在用户滚动 anchor 时自动将 anchor 的链接转到“id="selected"”。
最佳答案
试试这个 http://jsfiddle.net/8NKqf/1/
$(function() {
var anchors = $('.anchor');
var navLinks = $('.navigointi a');
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var clientHeight = document.documentElement.clientHeight;
var activeSectionAnchor, hash;
anchors.each(function() {
if ($(this).offset().top < scrollTop + clientHeight) {
activeSectionAnchor = $(this);
}
});
hash = "#" + activeSectionAnchor.attr('name');
activeLink = navLinks.removeClass('selected').filter('[href="' + hash + '"]');
activeLink.addClass('selected');
});
});
关于javascript - 让 JS 检测页面上的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19839661/