简体   繁体   English

单击锚链接时平滑滚动

[英]Smooth scrolling when clicking an anchor link

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.但请注意,他使用的是自定义 JavaScript 库。 Maybe jQuery offers somethings like this baked in?也许 jQuery 提供类似这样的东西?

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 time an 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 animate callback:如果您希望更新 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;
});

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 .因此只匹配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. \\\\是因为#是 css 选择器中的一个特殊字符,所以我们必须对其进行转义。

The new hotness in CSS3. CSS3 中的新热点。 This is a lot easier than every method listed on this page and requires no Javascript.这比此页面上列出的每种方法都要容易得多,并且不需要 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.只需在您的 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 id="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{} 中时,它终于奏效了。

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.现在您的内部链接滚动行为将像流一样流畅。

Programmatically: Something extra and advanced以编程方式:一些额外和高级的东西

// Scroll to specific values
// window.scrollTo or
window.scroll({
  top: 1000, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 250, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.getElementById('el').scrollIntoView({
  behavior: 'smooth'
})

Note : All latest browsers ( Opera , Chrome , Firefox etc) supports this feature.注意:所有最新的浏览器( OperaChromeFirefox等)都支持此功能。

for detail understanding, read this article详细了解,请阅读这篇 文章

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

this worked perfect for me这对我来说很完美

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-top CSS can be used to provide an offset.对于带有粘性标题的站点,可以使用scroll-padding-top CSS 来提供偏移量。

No need any js just use scroll-behavior: smooth at html tag Thats it不需要任何 js 只需使用 scroll-behavior: smooth at html 标签就是这样

html{
scroll-behavior: smooth;
}

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

$(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/

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

Using JQuery:使用 JQuery:

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

There is a css way of doing this using scroll-behavior.有一种使用滚动行为的 css 方法。 Add the following property.添加以下属性。

    scroll-behavior: smooth;

And that is it.就是这样。 No JS required.不需要JS。

 a { display: inline-block; width: 50px; text-decoration: none; } nav, scroll-container { display: block; margin: 0 auto; text-align: center; } nav { width: 339px; padding: 5px; border: 1px solid black; } scroll-container { display: block; width: 350px; height: 200px; overflow-y: scroll; scroll-behavior: smooth; } scroll-page { display: flex; align-items: center; justify-content: center; height: 100%; font-size: 5em; }
 <nav> <a href="#page-1">1</a> <a href="#page-2">2</a> <a href="#page-3">3</a> </nav> <scroll-container> <scroll-page id="page-1">1</scroll-page> <scroll-page id="page-2">2</scroll-page> <scroll-page id="page-3">3</scroll-page> </scroll-container>

PS: please check the browser compatibility. PS:请检查浏览器兼容性。

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

The answer given works but disables outgoing links.给出的答案有效但禁用传出链接。 Below a version with an added bonus ease out (swing) and respects outgoing links.在带有额外奖励的版本下方缓出(摆动)并尊重传出链接。

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

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

HTML HTML

<a href="#target" class="smooth-scroll">
    Link
</a>
<div id="target"></div>

or With absolute Full URL或使用绝对完整 URL

<a href="https://somewebsite.com/#target" class="smooth-scroll">
    Link
</a>
<div id="target"></div>

jQuery jQuery

$j(function() {
    $j('a.smooth-scroll').click(function() {
        if (
                window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
            &&  window.location.hostname == this.hostname
        ) {
            var target = $j(this.hash);
            target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $j('html,body').animate({
                    scrollTop: target.offset().top - 70
                }, 1000);
                return false;
            }
        }
    });
});

Modern browsers are a little faster these days.如今,现代浏览器的速度要快一些。 A setInterval might work. setInterval 可能会起作用。 This function work well in Chrome and Firefox these days.(A little slow in safari, didn't bother with IE)这个功能现在在 Chrome 和 Firefox 中运行良好。(在 safari 中有点慢,没有打扰 IE)

function smoothScroll(event) {
    if (event.target.hash !== '') { //Check if tag is an anchor
        event.preventDefault()
        const hash = event.target.hash.replace("#", "")
        const link = document.getElementsByName(hash) 
        //Find the where you want to scroll
        const position = link[0].getBoundingClientRect().y 
        let top = 0

        let smooth = setInterval(() => {
            let leftover = position - top
            if (top === position) {
                clearInterval(smooth)
            }

            else if(position > top && leftover < 10) {
                top += leftover
                window.scrollTo(0, top)
            }

            else if(position > (top - 10)) {
                top += 10
                window.scrollTo(0, top)
            }

        }, 6)//6 milliseconds is the faster chrome runs setInterval
    }
}

Adding this:添加这个:

function () {
    window.location.hash = href;
}

is somehow nullifying the vertical offset以某种方式使垂直偏移无效

top - 72

in Firefox and IE, ut not in Chrome.在 Firefox 和 IE 中,而不是在 Chrome 中。 Basically, the page scrolls smoothly to the point at which it should stop based upon the offset, but then jumps down to where the page would go without the offset.基本上,页面会根据偏移量平滑滚动到它应该停止的点,然后向下跳到页面没有偏移量的位置。

It does add the hash to the end of the url, but pressing back does not take you back to the top, it just removes the hash from the url and leaves the viewing window where it sits.它确实将散列添加到 url 的末尾,但按回不会将您带回到顶部,它只是从 url 中删除散列并将查看窗口留在它所在的位置。

Here is the full js I am using:这是我正在使用的完整 js:

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top - 120
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

This solution will also work for the following URLs, without breaking anchor links to different pages.此解决方案也适用于以下 URL,而不会破坏指向不同页面的锚链接。

http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor

./index.html
./index.html#anchor

etc.等等。

var $root = $('html, body');
$('a').on('click', function(event){
    var hash = this.hash;
    // Is the anchor on the same page?
    if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
        $root.animate({
            scrollTop: $(hash).offset().top
        }, 'normal', function() {
            location.hash = hash;
        });
        return false;
    }
});

I haven't tested this in all browsers, yet.我还没有在所有浏览器中测试过这个。

This will make it easy to allow jQuery to discern your target hash and know when and where to stop.这将使 jQuery 能够轻松识别您的目标哈希并知道何时何地停止。

$('a[href*="#"]').click(function(e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
$("a").on("click", function(event){
    //check the value of this.hash
    if(this.hash !== ""){
        event.preventDefault();

        $("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);

        //add hash to the current scroll position
        window.location.hash = this.hash;

    }



});

Tested and Verified Code经过测试和验证的代码

<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {

// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
  // Prevent default anchor click behavior
  event.preventDefault();

  // Store hash
  var hash = this.hash;

  // Using jQuery's animate() method to add smooth page scroll
  // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
  jQuery('html, body').animate({
    scrollTop: jQuery(hash).offset().top
  }, 800, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
  });
} // End if
});
});
</script>

For a more comprehensive list of methods for smooth scrolling, see my answer here .对于用于平滑滚动的方法更全面的列表,请参阅我的答案在这里


You can use window.scroll() with behavior: smooth and top set to the anchor tag's offset top which ensures that the anchor tag will be at the top of the viewport.您可以使用具有behavior: smooth window.scroll() behavior: smoothtop设置为锚标记的偏移顶部,以确保锚标记位于视口的顶部。

document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', function (e) {
        e.preventDefault();
        var href = this.getAttribute("href");
        var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
        //gets Element with an id of the link's href 
        //or an anchor tag with a name attribute of the href of the link without the #
        window.scroll({
            top: elem.offsetTop, 
            left: 0, 
            behavior: 'smooth' 
        });
        //if you want to add the hash to window.location.hash
        //you will need to use setTimeout to prevent losing the smooth scrolling behavior
       //the following code will work for that purpose
       /*setTimeout(function(){
            window.location.hash = this.hash;
        }, 2000); */
    });
});

Demo:演示:

 a, a:visited{ color: blue; } section{ margin: 500px 0px; text-align: center; }
 <a href="#section1">Section 1</a> <br/> <a href="#section2">Section 2</a> <br/> <a href="#section3">Section 3</a> <br/> <a href="#section4">Section 4</a> <section id="section1"> <b style="font-size: 2em;">Section 1</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/> <section> <section id="section2"> <b style="font-size: 2em;">Section 2</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <section id="section3"> <b style="font-size: 2em;">Section 3</b> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <a style="margin: 500px 0px; color: initial;" name="section4"> <b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b> </a> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <script> document.querySelectorAll('a[href^="#"]').forEach(a => { a.addEventListener('click', function (e) { e.preventDefault(); var href = this.getAttribute("href"); var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]"); window.scroll({ top: elem.offsetTop, left: 0, behavior: 'smooth' }); }); }); </script>

You can just set the CSS property scroll-behavior to smooth (which most modern browsers support) which obviates the need for Javascript.您可以将 CSS 属性scroll-behaviorsmooth (大多数现代浏览器都支持),这样就不需要 Javascript。

 html, body{ scroll-behavior: smooth; } a, a:visited{ color: blue; } section{ margin: 500px 0px; text-align: center; }
 <a href="#section1">Section 1</a> <br/> <a href="#section2">Section 2</a> <br/> <a href="#section3">Section 3</a> <br/> <a href="#section4">Section 4</a> <section id="section1"> <b style="font-size: 2em;">Section 1</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/> <section> <section id="section2"> <b style="font-size: 2em;">Section 2</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <section id="section3"> <b style="font-size: 2em;">Section 3</b> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <a style="margin: 500px 0px; color: initial;" name="section4"> <b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b> </a> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>

I did this for both "/xxxxx#asdf" and "#asdf" href anchors我为 "/xxxxx#asdf" 和 "#asdf" href 锚点做了这个

$("a[href*=#]").on('click', function(event){
    var href = $(this).attr("href");
    if ( /(#.*)/.test(href) ){
      var hash = href.match(/(#.*)/)[0];
      var path = href.match(/([^#]*)/)[0];

      if (window.location.pathname == path || path.length == 0){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
        window.location.hash = hash;
      }
    }
});

Here is the solution I implemented for multiple links and anchors, for a smooth scroll:这是我为多个链接和锚点实现的解决方案,以实现平滑滚动:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/ if you have your navigation links set up in a navigation div and declared with this structure: http://www.adriantomic.se/development/jquery-localscroll-tutorial/如果您在导航 div 中设置了导航链接并使用以下结构声明:

<a href = "#destinationA">

and your corresponding anchor tag destinations as so:以及您相应的锚标记目的地,如下所示:

<a id = "destinationA">

Then just load this into the head of the document:然后只需将其加载到文档的头部:

    <!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

<script type = "text/javascript">
 $(document).ready(function()
    {
        // Scroll the whole document
        $('#menuBox').localScroll({
           target:'#content'
        });
    });
</script>

Thanks to @Adriantomic感谢@Adriantomic

If you have a simple button on the page to scroll down to a div and want the back button to work by jumping to top, just add this code:如果页面上有一个简单的按钮可以向下滚动到 div 并且希望后退按钮通过跳到顶部来工作,只需添加以下代码:

$(window).on('hashchange', function(event) {
    if (event.target.location.hash=="") {
        window.scrollTo(0,0);
    }
});

This could be extended to jump to different divs too, by reading the hash value, and scrolling like Joseph Silbers answer.这也可以扩展到跳转到不同的 div,通过读取哈希值,并像 Joseph Silbers 回答一样滚动。

Never forget that offset() function is giving your element's position to document.永远不要忘记 offset() 函数正在为您的元素提供文档位置。 So when you need scroll your element relative to its parent you should use this;因此,当您需要相对于其父元素滚动元素时,您应该使用它;

    $('.a-parent-div').find('a').click(function(event){
        event.preventDefault();
        $('.scroll-div').animate({
     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       
  });

The key point is getting scrollTop of scroll-div and add it to scrollTop.关键是获取scroll-div的scrollTop并将其添加到scrollTop。 If you won't do that position() function always gives you different position values.如果你不这样做, position() 函数总是会给你不同的位置值。

thanks for sharing, Joseph Silber.感谢分享,约瑟夫·西尔伯。 Here your 2018 solution as ES6 with a minor change to keep the standard behavior (scroll to top):这里你的 2018 解决方案作为 ES6 进行了微小的更改以保持标准行为(滚动到顶部):

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

    const targetElement = document.querySelector(this.getAttribute("href"));
    targetElement.scrollIntoView({
      block: "start",
      alignToTop: true,
      behavior: "smooth"
    });
  });
});

Requires jquery and animates to anchor tag with the specified name instead of id, while adding the hash to browser url.需要 jquery 和 animates 使用指定的名称而不是 id 来锚定标签,同时将哈希添加到浏览器 url。 Also fixes an error in most answers with jquery where the # sign is not prefixed with an escaping backslash.还使用 jquery 修复了大多数答案中的错误,其中 # 符号没有以转义反斜杠为前缀。 The back button, unfortunately, does not navigate back properly to previous hash links...不幸的是,后退按钮无法正确导航回以前的哈希链接...

$('a[href*=\\#]').click(function (event)
{
    let hashValue = $(this).attr('href');
    let name = hashValue.substring(1);
    let target = $('[name="' + name + '"]');
    $('html, body').animate({ scrollTop: target.offset().top }, 500);
    event.preventDefault();
    history.pushState(null, null, hashValue);
});

Well, the solution depends on the type of problem, I use the javascript animate method for the button click.好吧,解决方案取决于问题的类型,我使用 javascript 动画方法来单击按钮。 and I use codes from bellow links for the navbar我使用来自导航栏的波纹管链接的代码

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

$(document).ready(function () {
  $(".js--scroll-to-plans").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-plans").offset().top,
      },
      1000
    );
    return false;
  });

  $(".js--scroll-to-start").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-features").offset().top,
      },
      1000
    );
    return false;
  });

  $('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
});

For users that are looking for a ReactJS (TypeScript) approach.对于正在寻找 ReactJS (TypeScript) 方法的用户。

function Hero() {
  const scrollToView = (e: any) => {
    e.preventDefault();
    // Scroll to a certain element
    document.getElementById("about-section")?.scrollIntoView({
      behavior: "smooth",
    });
  };
  return (
    <section id="hero">
        <button
          onClick={scrollToView} 
        >
          Learn More
        </button>    
    </section>
  );
}

export default Hero;

And for the about-section component对于about-section组件

const AboutSection = () => {
  return (
    <section id="about-section"  >
      <h1>About Section</h1>
    </section>
  );
};

export default AboutSection;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM