将类添加到<李>元素

Adding a class to a link inside a <li> element on scrolling

本文关键字:gt 元素 lt 添加      更新时间:2023-09-26

当页面的某个部分处于活动状态时,是否可以将类添加到li元素内的链接?

我有一个单页网站,当通过滚动到达页面的特定部分时,我想更改链接的颜色。

这是我的HTML:

<header id="header"> 
        <section class="container">
                <nav>
                    <a class="logo" href="index.html">Logo</a>
                    <div id="menu">
                        <ul id="links"> 
                            <li><a href="#services">Services</a></li>
                            <li><a href="#about">About</a></li>
                            <li><a href="#clients">Clients</a></li>  
                            <li class="last"><a href="#contact">Contact</a></li>
                        </ul>
                    </div>
                </nav>
        </section>
    </header>  

这是CSS:

#menu li a {
    color:#7a7a7a;
    text-decoration: none;
    font-size: 12px;
    margin-right:20px;
}
#menu li.last a {
    color:#7a7a7a;
    text-decoration: none;
    font-size: 12px;
    margin-right:0px;
}
#menu li.current a {
color: #0086be;
}

我想做的是,每当到达页面的特定部分时,将class.current添加到li元素内的链接中。

我相信只有使用Javascript才能实现这一点,有人能为我指明实现这一目标的正确途径吗?

提前感谢

我认为您希望在引导程序中使用类似于scrollspy的东西,你可以使用它,也可以找到https://gist.github.com/pascaldevink/2380129Bypascardevink

或者这是小提琴http://jsfiddle.net/ia_archiver/Kb7xq/

,你需要jquery

 $.fn.scrollspy = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('scrollspy')
        , options = typeof option == 'object' && option
      if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }
  $.fn.scrollspy.Constructor = ScrollSpy
  $.fn.scrollspy.defaults = {
    offset: 10
  }
  $(function () {
    $('[data-spy="scroll"]').each(function () {
      var $spy = $(this)
      $spy.scrollspy($spy.data())
    })
  })
}(window.jQuery);

使用悬停功能可以实现这一点。即,在悬停页面的特定部分时,将类添加到li内的链接中。例如

  $('#specificPartOfPageId').hover(function(){
      $('#links').children().children('a').addClass('current');
  });

这将把.current类添加到该UL元素内存在的每个链路
希望这能有所帮助。

如果我理解正确,我想这就是您所需要的:jsFiddle。CSS和HTML代码保持不变,这是我使用过的jQuery代码:

$(window).scroll(function() {    
var scroll = $(window).scrollTop();
if (scroll > 500) {
$("#links li:first-child").addClass("current");
}
if (scroll > 750) {
$("#links li:first-child").removeClass("current");
$("#links li:nth-child(2)").addClass("current");
}
var scrollBottom = $(window).scrollTop() + $(window).height();
if (scroll < 500) {
$("#links li:first-child").removeClass("current");
}
if (scroll < 750) {
$("#links li:nth-child(2)").removeClass("current");
}
});

基本上,当您向下滚动到500px时,li:first-child会自动分配给current类。您可以根据需要添加更多的if查询来修改jQuery以满足您的需求。您可以使用不同的子选择器(如li:first-childli:nth-child(2)等)瞄准列表中的不同<li>