繁体   English   中英

jQuery检测页面滚动后是否可见具有特定ID的元素

[英]JQuery detect if an element with particular id is visible after page scrolling

我要创建页面http://kiskolabs.com/上显示的导航

我已经创建了粘性菜单,但是问题开始于在菜单中标记活动元素。

问题是:

如何检测页面是否滚动到特定ID?

假设我有一些标题。

<h1 id="whatisit">What is it</h1>
<h1 id="desc">Description</h1>
<h1 id="faq">FAQ</h1>

和菜单

<nav>
  <a href="#whatisit">What is it</a>
  <a href="#desc">Description</a>
  <a href="#faq">FAQ</a>
</nav>

当页面滚动到此元素时,我要突出显示菜单(添加类或其他内容)。

我已经找到了如何在该线程中将元素滚动到特定的ID,但是我不知道如何检测现在的ID。 页面的大小是动态的,在内容显示期间可能会更改。 因此,我认为绝对的解决方案是不好的。

到目前为止,我得到的滚动内容是:

$("nav a").click(function (){
   $("html, body").animate({ scrollTop: $($(this).attr('href')).offset().top }, 1000);
});

我也找到了这种解决方案,但是也许有更好的方法来实现呢?

编辑

该问题与主持人建议的问题不重复。 此外,该问题没有公认的答案。 我的问题有点高级。

您可以使用动画回调函数:

$("nav a").click(function () {
    $("html, body").animate({
        scrollTop: $(this.href).offset().top
    }, 1000, function () {
        $(this).addclass('scrolled').siblings('h1').removeClass('scrolled');
    });
});

在尝试和寻找Internet解决方案的过程中,我已经解决了我的问题。

我使用了看起来非常易于使用的航点插件 插件可以在这里下载。

菜单的html代码:

        <nav>
            <a href="#whatisit" class="scrollable">....</a>
            <a href="#howworks"  class="scrollable">....</a>
            <a href="#whydata" class="scrollable" >....</a>
            <a href="#spec"  class="scrollable">...</a>
        </nav>

要滚动页面的标题的html代码:

<h2 class="scrollable" id="whatisit">...</h2>
<h2 class="scrollable" id="spec">...</h2>

jQuery代码 ,使页面在具有#id的特定元素上滚动,与a href属性相同。

$("nav a.scrollable").click(function (){
    var elementClickedHref = $(this).attr('href');
    $('html, body').animate({
                scrollTop: $(elementClickedHref).offset().top-100
                 }, 2000);  
    return false;
});

要更改滚动后当前处于活动状态的元素的颜色,我使用了Waypoint插件。 下面的代码找到可滚动的h2并获取其ID。 然后找出了可滚动链接太具有href作为ID同a元件,并增加了活性类给这个ID,并从非活动元件除去活性类。

$('h2.scrollable').waypoint(function() {
    var idToCheck = '#' + $(this).attr('id');
    $('a.scrollable').removeClass('active');
    $('a.scrollable[href="'+idToCheck+'"]').addClass('active');
}, {
    offset: '100%'
});

它可以按我的要求完美地工作。 我希望这种解决方案可以帮助遇到此类问题的人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM