单击特定链接时,将不同的偏移量设置为滚动顶部

Set different offset to scrolltop when a specific link is clicked

本文关键字:偏移量 设置 顶部 滚动 链接 单击      更新时间:2023-09-26

我现在有下面的代码,它工作得很好,当点击链接时会滚动到div的顶部。。。

$(function () {
  $('a[href*=#]:not([href=#])').click(function () {
    if (location.pathname.replace(/^'//, '') == this.pathname.replace(/^'//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({scrollTop: target.offset().top}, 1500);
        return false;
      }
    }
  });
});

然而,我想做的是,当点击一组特定的链接(#topbannerlinks a)时,它会滚动到div的顶部,但偏移量不同,例如

$("#topbannerlinks a").click(function(){
    $('html,body').animate({ scrollTop: target.offset().top -180 }, 1500);
});

我可以在上面的第一个函数中添加build这个函数/if语句吗?

我试着这样做,因为我在目标链接页面上有一个不同高度的标题,而且它不能正确地滚动到顶部。

您可以使用.is()检查某个元素是否也与另一个选择器匹配。例如,如果您的链接也匹配#topBanner a,则返回true;如果是另一个链接,则返回false:

$(myLink).is('#topBanner a');

因此,在.click()函数中,可以使用$(this).is('#topBanner a')进行此检查。

您不需要在代码中两次使用相同的animate函数,只需根据链接是否在#topBanner中设置偏移量,然后始终添加偏移量(无论是0还是180)

if (target.length) {
    // set 180 if link is in #topBanner, otherwise 0
    var offset = $(this).is('#topBanner a') ? 180 : 0; 
    $('html,body').animate({scrollTop: target.offset().top - offset}, 1500);
    return false;
}