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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8579643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:43:49  来源:igfitidea点击:

How to scroll up or down the page to an anchor using jQuery?

jqueryjquery-pluginsanchorslide

提问by ade123

I'm looking for a way to include a slide effect for when you click a link to a local anchor either up or down the page.

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

I'd like something where you have a link like so:

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

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

perhaps with a class added so you know you want this link to be a sliding link:

也许添加了一个类,所以你知道你希望这个链接是一个滑动链接:

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

Then if this link is clicked, the page slides up or down to the required place (could be a div, heading, top of page etc).

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



This is what I had previously:

这是我之前的情况:

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

回答by dknaack

Description

描述

You can do this using jQuery.offset()and jQuery.animate().

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

Check out the jsFiddle Demonstration.

查看jsFiddle 演示

Sample

样本

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

scrollToAnchor('id3');

More Information

更多信息

回答by Santi Nunez

Assuming that your hrefattribute is linking to a divwith the tag idwith the same name (as usual), you can use this code:

假设您的href属性链接到具有相同名称的标记iddiv(与往常一样),您可以使用以下代码:

HTML

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

回答by bobthenob

This made my life so much easier. You basically put in your elements id tag and its scrolls to it without a lot of code

这让我的生活变得轻松多了。你基本上把你的元素 id 标签和它的滚动到它没有很多代码

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

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

In Javascript

在 JavaScript 中

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

In your html

在你的 html

<div id="scroollto1">

Here I am all the way down the page

在这里,我一直在页面下方

回答by ipegasus

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

回答by Matt

You should also consider that the target has a padding and thus use positioninstead of offset. You can also account for a potential nav bar you don't want to be overlapping the target.

您还应该考虑目标具有填充,因此使用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 });
})

回答by Timo Huovinen

My approach with jQuery to just make all of the embedded anchor links slide instead of jump instantly

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

It's really similar to the answer by Santi Nunezbut it's more reliable.

它与Santi Nunez的答案非常相似,但更可靠

Support

支持

  • Multi-framework environment.
  • Before the page has finished loading.
  • 多框架环境。
  • 在页面加载完成之前。
<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);

回答by ade123

I stuck with my original code and also included a fade in 'back-to-top' link making use of this code and a bit from here too:

我坚持使用我的原始代码,还包括一个淡入淡出的“返回顶部”链接,使用此代码和这里的一些代码:

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

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

Works well :)

效果很好 :)

回答by TuxujPes

You may want to add offsetTopand scrollTopvalue in case You are animating not the whole page , but rather some nested content.

您可能想要添加offsetTopscrollTop值,以防您不是在为整个页面设置动画,而是为一些嵌套的内容设置动画。

e.g :

例如:

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

回答by Hastig Zusammenstellen

SS Slow Scroll

SS 慢速滚动

This solution does not require anchor tags but you do of course need to match the menu button (arbitrary attribute, 'ss' in example) with the destination element id in your html.

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

ss="about"takes you to id="about"

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/

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

回答by Ramtin

Here is the solution that worked for me. This is a generic function which works for all of the atags referring to a named a

这是对我有用的解决方案。这是一个通用函数,适用于所有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'); 
});

Note 1: Make sure that you use double quotes "in your html. If you use single quotes, change the above part of the code to var target = $("a[name='" + name.substring(1) + "']");

注意 1:确保"在 html 中使用双引号。如果使用单引号,请将上面的代码部分更改为var target = $("a[name='" + name.substring(1) + "']");

Note 2: In some cases, especially when you use the sticky bar from the bootstrap, the named awill hide beneath the navigation bar. In those cases (or any similar case), you can reduce the number of the pixels from your scroll to achieve the optimal location. For example: $('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');will take you to the targetwith 15 pixels left on the top.

注意 2:在某些情况下,尤其是当您使用引导程序中的粘性栏时,nameda将隐藏在导航栏下方。在这些情况下(或任何类似情况),您可以减少滚动中的像素数以达到最佳位置。例如:$('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');将带您到target顶部还剩 15 个像素的位置。