当有人滚动传递元素时,如何更改元素的属性(粘滞元素)

时间:2012-03-31 14:41:43

标签: javascript jquery

例如http://twitter.github.com/bootstrap/base-css.html尝试向上滚动。您将看到带有

的栏
  

“排版代码表表格按钮图标由Glyphicons”

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

编辑:我发现这是Sticky Element。

3 个答案:

答案 0 :(得分:2)

他们正在为此

使用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();
}); 

答案 1 :(得分:2)

这个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
   }
});

干杯

答案 2 :(得分:0)

他们正在跟踪滚动位置并修改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");
相关问题