我正在尝试通过检测具有特定 id 的 div 向导航中的链接添加一个类,每个 div 都在不同的页面上并位于顶部。
如果我对每个单独的实例使用它,分别更改 div 和类
$(document).on("scroll ready", function() {
if ($(this).scrollTop()>=$('#contact').position().top){
$("#nav .contact a").addClass("ur-here");
}
});
代码有效,除非我像这样重复使用该代码
$(document).on("scroll ready", function() {
if ($(this).scrollTop()>=$('#contact').position().top){
$("#nav .contact a").addClass("ur-here");
}
});
$(document).on("scroll ready", function() {
if ($(this).scrollTop()>=$('#blog').position().top){
$("#nav .blog a").addClass("ur-here");
}
});
此时只有第一个实例有效(第一个实例我的意思是我先放哪一部分并不重要,其余部分似乎被忽略)。 .
我也尝试过将它们全部包含在一个函数中
$(document).on("scroll ready", function() {
if ($(this).scrollTop()>=$('#intro').position().top){
$("#nav .home a").addClass("ur-here");
}
else if ($(this).scrollTop()>=$('#services').position().top){
$("#nav .service a").addClass("ur-here");
}
else if ($(this).scrollTop()>=$('#contact').position().top){
$("#nav .contact a").addClass("ur-here");
}
else if ($(this).scrollTop()>=$('#blog').position().top){
$("#nav .blog a").addClass("ur-here");
}
});
但同样只有第一个实例有效。
我也试过换掉
$(document).on("scroll ready", function() {
与
$(document).ready(function() {
和
$(window).load(function() {
有类似的结果,除非我使用
$(window).load(function() {
在第二种情况下,代码适用于它和第一种情况,但无论我使用什么,它都会继续忽略其余部分。
请帮忙
已编辑
如果有帮助,它是一个 wordpress 网站
解决了
我只是用
定位了单个“#”if ($("#mydiv").length > 0){
如果目标 div 存在并且长度大于 0,我可以让导航链接做一些事情。
最佳答案
如果您的目标是确保在向任一方向滚动时,您会在用户滚动到顶部的最底部 元素上显示 ur-here
类窗口进入,则:Live Example
$(document).on("scroll ready", function() {
// Remember scrollTop
var scrollTop = $(this).scrollTop();
// Remove the class from all relevant elements
$("#nav a").removeClass("ur-here");
// Working from the BOTTOM up, add it to the first matching element
if (scrollTop >=$('#blog').position().top) {
$("#nav .blog a").toggleClass("ur-here");
}
else if (scrollTop >=$('#contact').position().top) {
$("#nav .contact a").addClass("ur-here");
}
else {
// ...and so on
}
});
关于javascript - jquery addClass/removeClass 到基于 div 位置的导航链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24480763/