当滚动时特定的DIV出现时,我想将类“ selected”添加到a [href]。并在DIV完全滚动时删除该类。
这段代码添加了类,但是在完全滚动之后,a [href]没有聚焦。

var aChildren = $(".cd-faq-categories li a"); // 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);
}

$(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;
    // 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("selected");
    } else {
        if ($("a[href='#cld9']"))
        {
            //...
        }
        else
        {
            $("a[href='" + theID + "']").removeClass("selected");
        }
    }
}
if (windowPos + windowHeight == docHeight) {
    alert("gfg");
    if (!$(".cd-faq-categories li a").hasClass("selected")) {
        var navActiveCurrent = $("li").attr("href");
        $("a[href='" + navActiveCurrent + "']").removeClass("selected");
        $("li a").addClass("selected");
    }
}
});


正确的书写方式是什么?

最佳答案

 } else {
        if ($("a[href='#cld9']"))
        {
            //...
        }
        else
    {
        $("a[href='" + theID + "']").removeClass("selected");
    }
}


我想您可能希望最后一行针对所有其他ID运行,所以您需要

} else if ($("a[href='#cld9']")) {
            //...
} else {
            $("a[href='" + theID + "']").removeClass("selected");
}


代替

关于javascript - 在滚动jQuery上将css类切换为selected/unselected,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37405520/

10-12 00:16
查看更多