如何使用jQuery将页面滚动到锚点位置上或下?

204
我正在寻找一种方法,当单击页面内的本地锚点链接时,可以包含幻灯片效果,向上或向下滑动页面。我希望有这样一个链接:

我想要的是类似于以下链接:

<a href="#nameofdivetc">link text, img etc.</a>

也许你需要添加一个类来标识这个链接需要是一个滑动链接:

<a href="#nameofdivetc" class="sliding-link">link text, img etc.</a>

如果单击此链接,则页面会向上或向下滑动到所需位置(可能是

,标题,页面顶部等)。


这是我以前的内容:

    $(document).ready(function(){
    $(".scroll").click(function(event){
        //prevent the default action for the click event
        event.preventDefault();

        //get the full url - like mysitecom/index.htm#home
        var full_url = this.href;

        //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
        var parts = full_url.split("#");
        var trgt = parts[1];

        //get the top offset of the target anchor
        var target_offset = $("#"+trgt).offset();
        var target_top = target_offset.top;

        //goto that anchor by setting the body scroll top to anchor top
        $('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
    });
});
14个回答

462

描述

你可以使用 jQuery.offset()jQuery.animate() 来实现这个功能。

查看 jsFiddle演示

示例

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

scrollToAnchor('id3');

更多信息


64
这也可以通用化,以适用于页面中的所有内部锚链接:$("a[href^=#]").click(function(e) { e.preventDefault(); var dest = $(this).attr('href'); console.log(dest); $('html,body').animate({ scrollTop: $(dest).offset().top }, 'slow'); }); - bardo
@bardo,这个应该怎么实现?我用你的解决方案替换了dkmaack的,但是滑动效果没有出现(锚点本身是可用的)。我错过了什么吗? - jakub
2
@bardo,你还需要添加history.pushState(null, null, dest);,因为你正在阻止默认的位置哈希更改。 - Mike Causer
11
除了@bardo提供的解决方案之外,当你使用最新的jQuery时,你应该转义哈希符号,方法如下:$("a[href^=\#]")。 https://dev59.com/mmsz5IYBdhLWcg3wsaHN#18365991 - jaegs
1
动画化HTML和BODY的目的是什么?看起来像是我们不知道自己在做什么,只是把所有东西都做了。这会导致多个滚动条吗? - ygoe
显示剩余2条评论

49

假设您的 href 属性链接到一个具有相同名称的 id 标签的 div (通常如此),则可以使用以下代码:

HTML

<a href="#goto" class="sliding-link">Link to div</a>

<div id="goto">I'm the div</div>

JAVASCRIPT - (Jquery)

转化为中文是:

JAVASCRIPT - (Jquery)

$(".sliding-link").click(function(e) {
    e.preventDefault();
    var aid = $(this).attr("href");
    $('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});

1
非常简单但功能强大的解决方案,允许完全控制。我认为这个答案应该得到更多的赞。 - cronfy
同意,这是最好的解决方案,对我帮助很大。 - probablybest
它能工作,但打破了使用“name”的目的。当你使用“<a name="something"></a>”时,你也可以从外部引用它,然而,你的解决方案并没有提供那样的功能。 - Ramtin

13
function scroll_to_anchor(anchor_id){
    var tag = $("#"+anchor_id);
    $('html,body').animate({scrollTop: tag.offset().top},'slow');
}

3
真正的问题是,第二行的 +"" 有什么作用吗? - Rob
@Rob JavaScript 没有字符串插值,所以使用 + 连接字符串或变量,如 "#some_anchor"。实际上,我认为第二个连接 anchor_id + "" 是不必要的。 - onebree
1
谢谢@onebree,我想知道的是第二个concat :) - Rob

7
这让我的生活变得更加轻松。你只需输入元素的id标签,它就可以滚动到该位置,而不需要很多代码。

http://balupton.github.io/jquery-scrollto/

在Javascript中

$('#scrollto1').ScrollTo();

在你的html中
<div id="scroollto1">

我在页面的最下方


不起作用 - ScrollTo 不是一个函数。 - Dave Hilditch

6

您还应该考虑目标具有填充,因此应使用 position 而不是 offset。 您还可以考虑到可能存在导航栏,您不希望它覆盖目标。

您还应该注意目标元素周围的填充,并使用 position 属性来定位元素,而不是 offset 属性。如果有可能出现导航栏,您需要避免它与目标元素重叠。
const $navbar = $('.navbar');

$('a[href^="#"]').on('click', function(e) {
    e.preventDefault();

    const scrollTop =
        $($(this).attr('href')).position().top -
        $navbar.outerHeight();

    $('html, body').animate({ scrollTop });
})

在我看来,最好的解决方案是因为它不需要额外的类和令人讨厌的填充数学在CSS中用于固定导航栏。 - KSPR
但这并不会重写URL中的锚点标签。添加 history.pushState({}, "", this.href); 以保持URL更新。 - KSPR

5

我使用jQuery的方法是让所有嵌入式锚链接滑动而不是立即跳转

这个方法和Santi Nunez的答案非常相似,但更加可靠

支持

  • 多框架环境。
  • 页面加载前。
<a href="#myid">Go to</a>
<div id="myid"></div>

// Slow scroll with anchors
(function($){
    $(document).on('click', 'a[href^=#]', function(e){
        e.preventDefault();
        var id = $(this).attr('href');
        $('html,body').animate({scrollTop: $(id).offset().top}, 500);
    });
})(jQuery);

4

这是我找到的解决方案。这是一个通用函数,适用于所有引用命名 aa 标签。

$("a[href^=#]").on('click', function(event) { 
    event.preventDefault(); 
    var name = $(this).attr('href'); 
    var target = $('a[name="' + name.substring(1) + '"]'); 
    $('html,body').animate({ scrollTop: $(target).offset().top }, 'slow'); 
});

注意1:确保在您的HTML中使用双引号"。 如果您使用单引号,请将上述代码部分更改为var target = $("a[name='" + name.substring(1) + "']"); 注意2:在某些情况下,特别是在使用Bootstrap的粘性导航栏时,命名的a会隐藏在导航栏下面。 在这种情况(或任何类似情况)下,您可以减少滚动像素以实现最佳位置。 例如:$('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow'); 将带您到距离target顶部还剩15个像素的位置。

请务必使用 $("a[href^=\\#]") 转义您的 jQuery 选择器中的 # - Eric K

2

2

最简单的方法是:-

在 click 函数(Jquery)中:

$('html,body').animate({scrollTop: $("#resultsdiv").offset().top},'slow');

HTML

<div id="resultsdiv">Where I want to scroll to</div>

1
这段代码不会将锚点放入URL中。在动画之后添加 location.hash="#resultsdiv"; - Fanky

1

SS慢速滚动

此解决方案不需要锚标签,但您当然需要在html中将菜单按钮(任意属性,在示例中为“ss”)与目标元素ID匹配。

ss="about" 将带您到 id="about"

$('.menu-item').click(function() {
 var keyword = $(this).attr('ss');
 var scrollTo = $('#' + keyword);
 $('html, body').animate({
  scrollTop: scrollTo.offset().top
 }, 'slow');
});
.menu-wrapper {
  display: flex;
  margin-bottom: 500px;
}
.menu-item {
  display: flex;
  justify-content: center;
  flex: 1;
  font-size: 20px;
  line-height: 30px;
  color: hsla(0, 0%, 80%, 1);
  background-color: hsla(0, 0%, 20%, 1);
  cursor: pointer;
}
.menu-item:hover {
  background-color: hsla(0, 40%, 40%, 1);
}

.content-block-header {
  display: flex;
  justify-content: center;
  font-size: 20px;
  line-height: 30px;
  color: hsla(0, 0%, 90%, 1);
  background-color: hsla(0, 50%, 50%, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="menu-wrapper">
  <div class="menu-item" ss="about">About Us</div>
  <div class="menu-item" ss="services">Services</div>
  <div class="menu-item" ss="contact">Contact</div>
</div>

<div class="content-block-header" id="about">About Us</div>
<div class="content-block">
  Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.

That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="services">Services</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.

That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="contact">Contact</div>
<div class="content-block">
  Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.

That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>

Fiddle(小提琴)

https://jsfiddle.net/Hastig/stcstmph/4/


在我的情况下,它可以工作,但页面会跳到网站的顶部。我找不到原因。请问你能帮助我吗? - Khushbu Vaghela

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接