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

时间:2011-12-20 17:45:53

标签: jquery jquery-plugins anchor slide

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

我想要一个像你这样的链接的东西:

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

13 个答案:

答案 0 :(得分:393)

描述

您可以使用jQuery.offset()jQuery.animate()执行此操作。

查看jsFiddle Demonstration

示例

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

scrollToAnchor('id3');

更多信息

答案 1 :(得分:20)

假设您的 href 属性链接到 div 且标记 id 且名称相同(通常如此),您可以使用这段代码:

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

答案 2 :(得分:7)

这让我的生活变得更加轻松。你基本上把你的元素id标签和它的卷轴放到它上面而没有很多代码

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

在Javascript中

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

在你的HTML中

<div id="scroollto1">

这里我一直在页面上

答案 3 :(得分:6)

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

答案 4 :(得分:2)

我坚持使用我的原始代码,并且还包含了一个淡入“返回顶部”链接,使用此代码以及此处的一些内容:

http://webdesignerwall.com/tutorials/animated-scroll-to-top

运作良好:)

答案 5 :(得分:2)

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

答案 6 :(得分:1)

您可能需要添加 offsetTop scrollTop 值,以防您动画不是整个页面,而是一些嵌套内容。

例如:

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);

答案 7 :(得分:1)

最简单的方法是:-

在点击功能(jQuery)中:-

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

HTML

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

答案 8 :(得分:0)

SS Slow Scroll

此解决方案不需要锚标记,但您当然需要将菜单按钮(示例中的任意属性,&#39; ss&#39;)与html中的目标元素ID匹配。

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

&#13;
&#13;
$('.menu-item').click(function() {
	var keyword = $(this).attr('ss');
	var scrollTo = $('#' + keyword);
	$('html, body').animate({
		scrollTop: scrollTo.offset().top
	}, 'slow');
});
&#13;
.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);
}
&#13;
<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>
&#13;
&#13;
&#13;

<强>小提琴

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

答案 9 :(得分:0)

这是对我有用的解决方案。这是一个通用功能,适用于所有指向命名a的{​​{1}}标记

a

注1:确保在html中使用双引号$("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'); }); 。如果使用单引号,请将代码的以上部分更改为"

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

答案 10 :(得分: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);
      }
    }
  });

答案 11 :(得分:-1)

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

在此测试:

http://jsbin.com/ucati4

答案 12 :(得分:-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);
        }
    );