简体   繁体   English

滚动到最近的 href 选项卡 jquery

[英]scroll to closest href tab jquery

I'm trying to click a link and scroll to a tab that exists on my page.我正在尝试单击链接并滚动到我页面上存在的选项卡。 The issue is the id I am scrolling to exists twice on the page.问题是我滚动到的 id 在页面上存在两次。 When I click the scroll trigger it is scrolling to the id after the one I want to scroll to.当我单击滚动触发器时,它会滚动到我想要滚动到的那个之后的 id。 is there a way to use closest() or find the next tab with the specific ID?有没有办法使用最近的()或找到具有特定 ID 的下一个选项卡?

jquery:

   $('.link-to-management').click(function(e) {
        e.preventDefault();
        var linkTo = $(this).attr('href');

        $('html,body').animate({scrollTop:
            $(linkTo).offset().top - 55
        },350);
    });


html: 

 <a href="#to-management-tab" class="link-to-management">
 Assess response, adjust, and review</a>

div scrolling to:

<div class="tab-scroller__nav" id="to-management-tab"></div>

As you already know by the comments, multiple elements with the same ID is bad.正如您在评论中已经知道的那样,具有相同 ID 的多个元素是不好的。 Really bad.特别糟糕。 But I do understand that part of it is not under your control.但我明白其中的一部分不在你的控制之下。

So in that case, what I would do is tweaking the code a bit to work without ID's:所以在这种情况下,我会做的是稍微调整代码以在没有 ID 的情况下工作:

jQuery jQuery

$('.link-to-management').click(function(e) {
    e.preventDefault();
    var linkTo = $(this).attr('href');

    $('html,body').animate({scrollTop:
        $('[data-id=" + linkTo + "]').first().offset().top - 55
    },350);
});

HTML HTML

<a href="#to-management-tab" class="link-to-management">
Assess response, adjust, and review</a>

...

<div class="tab-scroller__nav" data-id="#to-management-tab"></div>

What Did I Do?我做了什么?

Not much, if you really need to know.不多,如果你真的需要知道的话。 Just changed the id into data-id so you don't get punished for using same ID twice, updating the jQuery selector so it can handle the new data-id attribute, and adding first() so it chooses the first element as you mentioned.只是将id更改为data-id这样您就不会因两次使用相同的 ID 而受到惩罚,更新 jQuery 选择器以便它可以处理新的data-id属性,并添加first()以便它选择您提到的第一个元素.

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

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