Javascript 单击锚链接时平滑滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7717527/
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-24 03:19:28  来源:igfitidea点击:

Smooth scrolling when clicking an anchor link

javascriptjqueryscrollhyperlinkanchor

提问by Only Bolivian Here

I have a couple of hyperlinks on my page. A FAQ that users will read when they visit my help section.

我的页面上有几个超链接。用户在访问我的帮助部分时会阅读的常见问题解答。

Using Anchor links, I can make the page scroll towards the anchor and guide the users there.

使用锚链接,我可以使页面向锚滚动并引导用户到达那里。

Is there a way to make that scrolling smooth?

有没有办法使滚动平滑?

But notice that he's using a custom JavaScript library. Maybe jQuery offers somethings like this baked in?

但请注意,他使用的是自定义 JavaScript 库。也许 jQuery 提供了这样的东西?

回答by Joseph Silber

Update April 2018:There's now a native way to do this:

2018 年 4 月更新:现在有一种本地方法可以做到这一点

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

This is currently only supported in the most bleeding edge browsers.

这目前仅在最前沿的浏览器中受支持。



For older browser support, you can use this jQuery technique:

对于较旧的浏览器支持,您可以使用以下 jQuery 技术:

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

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

And here's the fiddle: http://jsfiddle.net/9SDLw/

这是小提琴:http: //jsfiddle.net/9SDLw/



If your target element does not have an ID, and you're linking to it by its name, use this:

如果您的目标元素没有 ID,并且您通过它的 链接到它name,请使用:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);

    return false;
});


For increased performance, you should cache that $('html, body')selector, so that it doesn't run every single timean anchor is clicked:

为了提高性能,您应该缓存该$('html, body')选择器,这样它就不会在每次单击锚点运行:

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});


If you want the URL to be updated, do it within the animatecallback:

如果您希望更新 URL,请在animate回调中执行此操作:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});

回答by Andres Separ

The correct syntax is:

正确的语法是:

//Smooth scrolling with links
$('a[href*=\#]').on('click', function(event){     
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});

// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
  $('html,body').animate({scrollTop:$(location.hash).offset().??top}, 500);
});

Simplifying: DRY

简化:干

function smoothScrollingTo(target){
  $('html,body').animate({scrollTop:$(target).offset().?top}, 500);
}
$('a[href*=\#]').on('click', function(event){     
    event.preventDefault();
    smoothScrollingTo(this.hash);
});
$(document).ready(function(){
  smoothScrollingTo(location.hash);
});

Explanation of href*=\\#:

的解释href*=\\#

  • *means it matches what contains #char. Thus only match anchors. For more about the meaning of this, see here
  • \\is because the #is a special char in css selector, so we have to escape it.
  • *意味着它匹配包含#字符的内容。因此只匹配anchors。有关此含义的更多信息,请参见此处
  • \\是因为#css 选择器中的特殊字符,所以我们必须转义它。

回答by Cristian Reyes

The new hotness in CSS3. This is a lot easier than every method listed on this page and requires no Javascript. Just enter the below code into you css and all of a sudden links point to locations inside you own page will have a smooth scrolling animation.

CSS3 中的新热点。这比此页面上列出的每种方法都要容易得多,并且不需要 Javascript。只需在您的 css 中输入以下代码,突然间指向您自己页面内位置的链接将具有平滑的滚动动画。

html{scroll-behavior:smooth}

After that any links pointed towards a div will smoothly glide over to those sections.

之后,指向 div 的任何链接都将平滑地滑到这些部分。

<a href="#section">Section1</a>

Edit: For those confused about the above a tag. Basically it's a link that's clickable. You can then have another div tag somewhere in your web page like

编辑:对于那些对上述标签感到困惑的人。基本上它是一个可点击的链接。然后你可以在你的网页中的某个地方有另一个 div 标签,比如

<div classname="section">content</div>

In this regard the a link will be clickable and will go to whatever #section is, in this case it's our div we called section.

在这方面,a 链接将是可点击的,并将转到任何 #section,在这种情况下,它是我们称为 section 的 div。

BTW, I spent hours trying to get this to work. Found the solution in some obscure comments section. It was buggy and wouldn't work in some tags. Didn't work in the body. It finally worked when I put it in html{} in the CSS file.

顺便说一句,我花了几个小时试图让它发挥作用。在一些晦涩的评论部分找到了解决方案。它有问题,在某些标签中不起作用。对身体不起作用。当我把它放在 CSS 文件的 html{} 中时,它终于奏效了。

回答by Philipp Sander

$('a[href*=#]').click(function(event){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    event.preventDefault();
});

this worked perfect for me

这对我来说很完美

回答by coco puffs

I'm surprised no one has posted a native solution that also takes care of updating the browser location hash to match. Here it is:

我很惊讶没有人发布了一个本地解决方案,该解决方案还负责更新浏览器位置哈希以进行匹配。这里是:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
?
for (let item of anchorlinks) { // relitere 
????item.addEventListener('click', (e)=> {
????????let hashval = item.getAttribute('href')
????????let target = document.querySelector(hashval)
????????target.scrollIntoView({
????????????behavior: 'smooth',
????????????block: 'start'
????????})
????????history.pushState(null, null, hashval)
????????e.preventDefault()
????})
}

See tutorial: http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml

见教程:http: //www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml

For sites with sticky headers, scroll-padding-topCSS can be used to provide an offset.

对于带有粘性标题的站点,scroll-padding-topCSS 可用于提供偏移量。

回答by WasiF

Only CSS

只有 CSS

html {
    scroll-behavior: smooth !important;
}

All you need to add only this. Now your internal links scrolling behavior will be smooth like a stream-flow.

所有你需要添加的只是这个。现在您的内部链接滚动行为将像流一样流畅。

Note: All latest browsers (Opera, Chrome, Firefoxetc) supports this feature.

:所有最新的浏览器(OperaChromeFirefox等)支持此功能。

for detail understanding, read this article

详细了解,请阅读这篇文章

回答by sarah bouyer

I suggest you to make this generic code :

我建议你制作这个通用代码:

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

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

return false;});

You can see a very good article here : jquery-effet-smooth-scroll-defilement-fluide

你可以在这里看到一篇很好的文章:jquery-effet-smooth-scroll-defilement-fluide

回答by KingRider

$(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
        }, 1000);
        return false;
      }
    }
  });
});

Official: http://css-tricks.com/snippets/jquery/smooth-scrolling/

官方:http: //css-tricks.com/snippets/jquery/smooth-scrolling/

回答by Blackbam

There are already a lot of good answers here - however they are all missing the fact that empty anchors have to be excluded. Otherwise those scripts generate JavaScript errors as soon as an empty anchor is clicked.

这里已经有很多好的答案——但是它们都忽略了必须排除空锚点的事实。否则,一旦单击空锚点,这些脚本就会生成 JavaScript 错误。

In my opinion the correct answer is like this:

在我看来,正确的答案是这样的:

$('a[href*=\#]:not([href$=\#])').click(function() {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

回答by Lalnuntluanga Chhakchhuak

There is native support for smooth scrolling on hash id scrolls.

对哈希 id 滚动的平滑滚动有本机支持。

html {
  scroll-behavior: smooth;
}

You can take a look: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

你可以看看:https: //www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2