【问题标题】:jQuery : add css class to menu item based on browser scroller positionjQuery:根据浏览器滚动位置将css类添加到菜单项
【发布时间】:2011-02-11 18:49:06
【问题描述】:

我有一个菜单:

  <ul class="menu-bottom">
  <li id="m1" class="active"><a id="1" href="#"><span>Link 1</span></a></li>
   <li id="m2"><a id="2" href="#"><span>Link 2</span></a></li>
   <li id="m3"><a id="3" href="#"><span>Link 3</span></a></li>
</ul>

我希望根据浏览器的滚动条位置,"active" 类进入正确的 元素。

这就是我的看法:

     if ($(document).height() == 500) {
$('#m1').parent().addClass('active').
siblings().removeClass('active');
}

     if ($(document).height() == 1000) {
$('#m2').parent().addClass('active').
siblings().removeClass('active');
}

     if ($(document).height() == 1500) {
$('#m2').parent().addClass('active').
siblings().removeClass('active');
} 

我对 jQuery 维度属性不是很熟悉,所以这段代码没有多大意义,但我希望你能明白。

如果有人能告诉我如何完成这项工作,那就太好了。

谢谢:)

【问题讨论】:

    标签: jquery browser scroll dimensions


    【解决方案1】:

    目前尚不完全清楚您要做什么,但我会试一试。要获得窗口垂直滚动的量,您需要使用 jQuery 的 scrollTop() 函数。 height() 函数为您提供调用它的元素的高度(以像素为单位),因此如果滚动值是您想要的,它不会很有用。这样的东西可能更接近您的需要:

    // bind a function to the window's scroll event, this will update
    // the 'active' class every time the user scrolls the window
    $(window).scroll(function() {    
        // find the li with class 'active' and remove it
        $("ul.menu-bottom li.active").removeClass("active");
        // get the amount the window has scrolled
        var scroll = $(window).scrollTop();
        // add the 'active' class to the correct li based on the scroll amount
        if (scroll <= 500) {
            $("#m1").addClass("active");
        }
        else if (scroll <= 1000) {
            $("#m2").addClass("active");
        }
        else {
            $("#m3").addClass("active");
        }
    }
    

    即使上述内容不在正确的轨道上,还有其他一些需要注意的事项可能会有所帮助。 $('#m1').parent().addClass('active').siblings().removeClass('active'); 之类的行可能没有按照您的预期进行。与其将“活动”类添加到 li,然后将其从 li 的兄弟姐妹中删除,它实际上是将该类添加到父 ul 并将其从 ul 的兄弟姐妹中删除。尝试从每一行中删除.parent(),这应该可以。

    此外,由于您在 if 条件中使用 ==,因此仅当值恰好为 500 或 1000 等时才会添加该类。我怀疑这是否是您想要的。这就是为什么在上面的代码中我将其更改为

    希望这会有所帮助。

    【讨论】:

    • 非常感谢!它完全符合我的要求:)
    • 没问题。很高兴我能帮上忙。
    • 我认为你不见了 );在你的最后一行...谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    相关资源
    最近更新 更多