如何使用jQuery上下滚动页面至锚点?


176

我正在寻找一种在您单击页面上方或下方指向本地锚点的链接时包含幻灯片效果的方法。

我想要一些您有这样链接的东西:

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

也许添加了一个类,所以您知道希望此链接为滑动链接:

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

然后,如果单击此链接,页面将向上或向下滑动到所需位置(可以是div,标题,页面顶部等)。


这是我以前的经历:

    $(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');
    });
});

Answers:


427

描述

您可以使用jQuery.offset()和进行此操作jQuery.animate()

查看jsFiddle演示

样品

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

scrollToAnchor('id3');

更多信息


52
也可以将其设为通用,以与页面中的所有内部锚链接一起使用:$("a[href^=#]").click(function(e) { e.preventDefault(); var dest = $(this).attr('href'); console.log(dest); $('html,body').animate({ scrollTop: $(dest).offset().top }, 'slow'); });
bardo 2014年

@bardo,应该如何实施?我用您的解决方案代替了dkmaack的解决方案,但是滑动不存在(锚点本身是有效的)。我想念什么?
jakub 2015年

1
@bardo还会添加,history.pushState(null, null, dest);因为您要防止默认位置哈希值更改
Mike Causer 2015年

7
仅供参考,除了@bardo的解决方案之外,在使用最新的jQuery这样的$(“ a [href ^ = \\#]”)stackoverflow.com/questions/7717527/…
jaegs

1
同时为html和body动画的目的是什么?看起来就像是一种情况,我们不知道该怎么做,而只是做所有事情。这可能会引发多个问题吗?
ygoe

28

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

的HTML

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

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

JAVASCRIPT-(jQuery)

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

1
非常简单但功能强大的解决方案,可以实现完全控制。我认为这个答案应该得到更多的支持。
cronfy

同意,这是最好的解决方案,对我有很大帮助
可能

它有效,但无法达到使用目的name。使用时<a name="something"></a>,您也可以从外部引用它,但是您的解决方案不提供此功能。
拉汀

8

这使我的生活变得更加轻松。基本上,您无需输入大量代码就可以将其元素id标签放入其中并滚动到它

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

用JavaScript

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

在你的HTML

<div id="scroollto1">

我一直在这里


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

3
真正的问题,+“”在第二行是否有作用?
罗布

@Rob javascript没有字符串插值,因此+与字符串或vars结合使用可以将它们串联起来,例如:"#some_anchor"anchor_id + ""我相信,确实不需要第二次会议。
2013年

谢谢@onebree这是我想知道的第二次会议:)
Rob

5

您还应该考虑到目标具有填充,因此使用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);以保持网址更新
KSPR

3

我使用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);


1

如果您不是要动画整个页面,而是要动画一些嵌套的内容,则可能需要添加offsetTopscrollTop值。

例如:

var itemTop= $('.letter[name="'+id+'"]').offset().top;
var offsetTop = $someWrapper.offset().top;
var scrollTop = $someWrapper.scrollTop();
var y = scrollTop + letterTop - offsetTop

this.manage_list_wrap.animate({
  scrollTop: y
}, 1000);

0

SS慢滚动

该解决方案不需要锚标记,但是您当然需要将菜单按钮(任意属性,例如'ss')与html中的目标元素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>

小提琴

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


0

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

$("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:在某些情况下,尤其是当您使用引导程序中的粘滞栏时,名称a将隐藏在导航栏下方。在这些情况下(或任何类似情况),您可以减少滚动条中的像素数量,以达到最佳位置。例如:$('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');将带您到target顶部还有15个像素的。


0

我在https://css-tricks.com/snippets/jquery/smooth-scrolling/上偶然发现了这个示例,解释了每一行代码。我发现这是最好的选择。

https://css-tricks.com/snippets/jquery/smooth-scrolling/

您可以本地化:

window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth' 
});

window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

或与jQuery:

$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {

    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) {
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
      }
    }
  });

0

确定最简单的方法是:-

在点击功能(jQuery)中:-

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

的HTML

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

-1
$(function() {
    $('a#top').click(function() {
        $('html,body').animate({'scrollTop' : 0},1000);
    });
});

在这里测试:

http://jsbin.com/ucati4


3
请不要包括签名,特别是带有链接的签名...,尤其是带有不相关链接的签名。您可以在个人资料中放入这类内容。
Andrew Barber

问的问题不是如何滚动到页面顶部,而是如何滚动到具有ID的锚点
user1380540 2015年

我可以在WordPress中使用该方法吗?将其添加到我的网站中,但实际上并不起作用。这里的链接:scentology.burnnotice.co.za
用户代理

-1

以下解决方案为我工作:

$("a[href^=#]").click(function(e)
        {
            e.preventDefault();
            var aid = $(this).attr('href');
            console.log(aid);
            aid = aid.replace("#", "");
            var aTag = $("a[name='"+ aid +"']");
            if(aTag == null || aTag.offset() == null)
                aTag = $("a[id='"+ aid +"']");

            $('html,body').animate({scrollTop: aTag.offset().top}, 1000);
        }
    );
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.