当有人滚动经过某个元素时,我如何更改该元素的属性(粘滞元素)

How do I change an attribute of an element when someone scroll pass the element (Sticky Element)

本文关键字:元素 何更改 属性 滚动 经过      更新时间:2023-09-26

例如http://twitter.github.com/bootstrap/base-css.html试着向上滚动。你会看到带有的酒吧

"打字代码表按Glyphicons形成按钮图标"

当您滚动传递元素时,它将添加一个类来更改元素。当您向上滚动时,它将删除属性以再次更改元素。

编辑:我发现这就是所谓的粘性元素。

jQUery插件可以随心所欲:http://imakewebthings.com/jquery-waypoints/

下面是一个来自URL的示例:

someElements.waypoint(function(event, direction) {
   if (direction === 'down') {
      // do this on the way down
   }
   else {
      // do this on the way back up through the waypoint
   }
});

干杯

他们正在为这个使用addClass()函数

$(".subnav").addClass("subnav-fixed");

这是他们在这个中使用的功能

function processScroll() {
    var i, scrollTop = $win.scrollTop() //get the scroll position of the window object
    if (scrollTop >= navTop && !isFixed) { //check if its position is higher that the position of the navigation
    isFixed = 1 //if yes fix it
    $nav.addClass('subnav-fixed')
} else if (scrollTop <= navTop && isFixed) { //if is not higher then
    isFixed = 0
    $nav.removeClass('subnav-fixed') //un fix it
}
}

他们在文档的滚动事件中调用此函数。可能类似

$(document).scroll(function() {
    processScroll();
}); 

他们正在跟踪滚动位置并修改li元素上的类

您看到的子导航栏是使用ul和li元素实现的。你可以从firebug中看到:

<div class="subnav subnav-fixed">
    <ul class="nav nav-pills">
      <li class=""><a href="#typography">Typography</a></li>
      <li class=""><a href="#code">Code</a></li>
      <li class="active"><a href="#tables">Tables</a></li>
      <li class=""><a href="#forms">Forms</a></li>
      <li class=""><a href="#buttons">Buttons</a></li>
      <li class=""><a href="#icons">Icons by Glyphicons</a></li>
    </ul>
  </div>

请注意,他们是如何为要激活的导航元素设置class='active'的。

使用Jquery,您需要选择li元素并将其更改为类。有很多方法可以选择您想要的元素(通过id、子选择器、类选择器等)看见http://api.jquery.com/category/selectors/

要更改类,可以使用toggleClass、addClass和removeClass函数来操作所需元素的类

例如,你可以做

 //remove any active elements
 $("ul.nav > li").removeClass("active");
 //Make the 'Tables' subnav element active
 $("ul.nav > li:contains('Tables')").addClass("active");

注意,:contains可能有点重,因为它查找所选元素内的所有文本。您可以使用其他选择器,如:eq或nth-child看见http://api.jquery.com/nth-child-selector/

$("ul.nav li:eq(2)").addClass( "active");