首页 > 解决方案 > JQuery position() 和 offset() 方法不起作用

问题描述

我是一名初学者程序员,我正在尝试创建这种效果,当我滚动浏览 HTML 中的特定元素时,导航栏中按钮的颜色会改变颜色。我认为这样做的正确方法是 jQuery。我在获取页面中元素的位置时遇到问题。我尝试过使用 position() 和 offset() 方法。但似乎两者都不起作用。

我想获得 ID 为“info”和“security”的元素的垂直位置。我有这些方法在某些情况下不是很可靠,但我找不到替代方法。

这是我到目前为止的代码:

   $(window).on('load', function(){ 
      window.loaded = true;
      console.log("LOADED");
    });
    $( window ).scroll(function() {
      if (window.loaded == true){  
        var scrollTop = $(window).scrollTop();
        var infopos = $( "#info" );
        var secpos = $("#security");

        if (scrollTop >= 0 && scrollTop < infopos-25) {
            $( "#navgeneral" ).addClass("active");
            $( "#navinfo" ).removeClass("active");
            $( "#navsecurity" ).removeClass("active");
        }
        else if (scrollTop >= infopos && scrollTop < secpos){
            $( "#navgeneral" ).removeClass("active");
            $( "#navinfo" ).addClass("active");
            $( "#navsecurity" ).removeClass("active");
        }
      }    
    });`

提前谢谢你的建议!!

标签: javascripthtmljquerycss

解决方案


提到的目标是让 NAV 栏根据您滚动到的位置发生变化。首先,您需要获取目标 ID 滚动位置。使用以下代码获取每个 Archor 元素 ID:

$('#testB').position().top

(在jQuery中,位置会返回给你left和top的值,这里我们只使用top。)其次,获取当前的滚动位置。使用下面的代码:

currentHeight = $(window).scrollTop();

第三,编写相关的jQuery代码来改变NAV元素。示例JS如下:这里我们有5个DIV(#testA到E)和4个导航按钮(#test1到4)

$(window).scroll(function () {
var currentHeight = $(window).scrollTop();
if (currentHeight <= $('#testB').position().top) {
    $("#test1").addClass('active-blue');
    $("#test2").removeClass('active-blue');
    $("#test3").removeClass('active-blue');
    $("#test4").removeClass('active-blue');
} else if (currentHeight <= $('#testC').position().top) {
    $("#test1").removeClass('active-blue');
    $("#test2").addClass('active-blue');
    $("#test3").removeClass('active-blue');
    $("#test4").removeClass('active-blue');
} else if (currentHeight <= $('#testD').position().top) {
    $("#test1").removeClass('active-blue');
    $("#test2").removeClass('active-blue');
    $("#test3").addClass('active-blue');
    $("#test4").removeClass('active-blue');
} else {
    $("#test1").removeClass('active-blue');
    $("#test2").removeClass('active-blue');
    $("#test3").removeClass('active-blue');
    $("#test4").addClass('active-blue');
}

});


推荐阅读