jquery - 滚动时突出显示标题

标签 jquery scroll highlight

我已将 session 设置为行。

<div class="container" id="session1">
  <div class="row session">
    <div class="fourcol">
        <h2>Session 3:</h2>
    </div>

     <div class="fourcol last">
         <p> Information about session </p>
    </div>

  </div>
</div>

我有很多这样的 session ,需要一种方法来突出显示您正在阅读 session 1。我想添加 .selected类(class) <h2 class="selected">Session 3:</h2>当你滚动过去时。

我希望这也会添加 .selected类是否有任何传入的 anchor 链接。到/sessions#session1 因为它必须“滚动”到该位置

任何帮助都会很棒。谢谢。

最佳答案

我建议您查看jQuery Waypoints ,它正是您正在寻找的东西,而且易于使用。

Here's an example我制作了,当使用 jQuery Waypoints 将元素滚动到视口(viewport)时,我添加了 .selected 类。

<小时/>

您当然也可以自己做,但您会做 Waypoint 已经在做的事情。
首先使用.scroll event在文档或所需元素上捕获您想要的特定事件。

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

然后使用 .scrollTop检查您所在的位置,并根据视口(viewport)(即窗口)添加元素必须位于其中的“边界”。

$(document).scroll(function(e){
    var bound_top = $(this).scrollTop(),
        bound_bottom = bound_top + $(window).height();
});

然后检查每个标题/部分元素以查看它们是否在这些边界内

$(document).scroll(function(e){
    var bound_top = $(this).scrollTop(),
        bound_bottom = bound_top + $(window).height();

    $("h2").each(function(){
        if( 
            $(this).position().top >= bound_top &&
            $(this).position().top + $(this).outerHeight() <= bound_bottom
        ){
            $(this).addClass("selected");
        }else{
            $(this).removeClass("selected");
        }
    }
});

它看起来有点像 in this example我做的。

这种方法可以让您完全按照自己想要的方式做事。
jQuery Waypoints 是一个很好且快速的替代方案。

关于jquery - 滚动时突出显示标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474582/

相关文章:

javascript - 使用 HTML/JavaScript/CSS 隐藏隐藏元素

python - 在 qtablewidget 中寻找信号

css - 在 div 内向上(而不是向下)增长的列表,然后滚动

jquery - 如何将 ASP.NET MVC 3 页面的 HTML 获取到 QUnit 测试中?

javascript - GeoJSON 层数组与 PanelLayers : Layer undefined

jquery - 位置:固定水平滚动

android - 线性布局 - 只有 RecyclerView 滚动

WPF MVVM ListBox SelectedItem 未突出显示

jquery - 如何在突出显示文本后启用弹出窗口?

emacs - 如何在 Emacs 中突出显示 CVS 更改?