单击锚链接时平滑滚动

Posted

技术标签:

【中文标题】单击锚链接时平滑滚动【英文标题】:Smooth scrolling when clicking an anchor link 【发布时间】:2011-12-04 18:36:36 【问题描述】:

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

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

有没有办法让滚动流畅?

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

【问题讨论】:

能否请您查看最佳答案?在所有庞大的 jquery 建议中很难找到纯 css 的单行解决方案:***.com/a/51588820/1422553 【参考方案1】:

2018 年 4 月更新:现在有a native way to do this:

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

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

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


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

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

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

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


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

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

    return false;
);

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

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

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

    return false;
);

如果您希望更新 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;
);

【讨论】:

我认为在此处缓存 html, body 对象是不必要的,每次点击运行一次选择器并没有那么多。【参考方案2】:

正确的语法是:

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

简化:干

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

href*=\\#的解释:

* 表示它与包含 # 字符的内容匹配。因此只匹配 anchors。有关此含义的更多信息,请参阅here \\ 是因为 # 是 css 选择器中的特殊字符,所以我们必须对其进行转义。

【讨论】:

【参考方案3】:
$('a[href*=#]').click(function(event)
    $('html, body').animate(
        scrollTop: $( $.attr(this, 'href') ).offset().top
    , 500);
    event.preventDefault();
);

这对我来说很完美

【讨论】:

【参考方案4】:

使用 JQuery:

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

【讨论】:

【参考方案5】:

添加这个:

function () 
    window.location.hash = href;

以某种方式使垂直偏移无效

top - 72

在 Firefox 和 IE 中,而不是在 Chrome 中。基本上,页面会根据偏移量平滑滚动到它应该停止的点,然后向下跳转到没有偏移量的页面。

它确实将哈希添加到 url 的末尾,但按返回不会带您回到顶部,它只是从 url 中删除哈希并离开它所在的查看窗口。

这是我正在使用的完整 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;
);

【讨论】:

【参考方案6】:

我为“/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;
      
    
);

【讨论】:

【参考方案7】:
$(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;
      
    
  );
);

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

【讨论】:

这似乎只适用于内页锚链接,但来自其他页面的锚链接不起作用,例如website.com/about-us/#who-we-are【参考方案8】:

这是我为多个链接和锚点实现的解决方案,以实现平滑滚动:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/ 如果您在导航 div 中设置导航链接并使用此结构声明:

<a href = "#destinationA">

以及您相应的锚标记目的地:

<a id = "destinationA">

然后将其加载到文档的头部:

    <!-- 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>

感谢@Adriantomic

【讨论】:

【参考方案9】:

如果您在页面上有一个简单的按钮可以向下滚动到一个 div,并希望 后退按钮 通过跳到顶部来工作,只需添加以下代码:

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

这也可以扩展到跳转到不同的 div,方法是读取哈希值,并像 Joseph Silbers 回答那样滚动。

【讨论】:

【参考方案10】:

此解决方案也适用于以下 URL,而不会破坏指向不同页面的锚链接。

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

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

等等

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

我还没有在所有浏览器中测试过这个。

【讨论】:

【参考方案11】:

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

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

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

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

return false;);

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

【讨论】:

【参考方案12】:

这将使 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;
    );
);

【讨论】:

【参考方案13】:

永远不要忘记 offset() 函数将元素的位置提供给文档。因此,当您需要相对于其父元素滚动元素时,您应该使用它;

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

关键是获取scroll-div的scrollTop并将其添加到scrollTop。如果你不这样做,那么 position() 函数总是会给你不同的位置值。

【讨论】:

【参考方案14】:
$("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;

    



);

【讨论】:

【参考方案15】:

经过测试和验证的代码

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

【讨论】:

【参考方案16】:

给出的答案有效,但禁用传出链接。下面是一个带有额外奖励的版本缓出(摇摆)并尊重传出链接。

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

【讨论】:

【参考方案17】:

HTML

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

或使用绝对完整网址

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

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

【讨论】:

【参考方案18】:

如今,现代浏览器的速度要快一些。一个 setInterval 可能会起作用。这个功能现在在 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
    

【讨论】:

【参考方案19】:

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

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

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

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

【讨论】:

【参考方案20】:

感谢分享,约瑟夫·西尔伯。在这里,您的 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"
    );
  );
);

【讨论】:

【参考方案21】:

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

htmlscroll-behavior:smooth

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

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

编辑:对于那些对上述标签感到困惑的人。基本上它是一个可点击的链接。然后,您可以在网页中的某个位置添加另一个 div 标签,例如

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

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

顺便说一句,我花了几个小时试图让它工作。在一些不起眼的 cmets 部分找到了解决方案。它有问题,在某些标签中不起作用。没有在体内起作用。当我将它放在 CSS 文件中的 html 中时,它终于起作用了。

【讨论】:

我可以很方便,但他们are drawbacks 不错,但要小心,因为目前 Safari 和资源管理器 (03/2019) 不支持它【参考方案22】:

更全面的平滑滚动方法列表见我的回答here。


您可以使用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); */
    );
);

演示:

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>

您可以将 CSS 属性 scroll-behavior 设置为 smooth(大多数现代浏览器都支持),这样就不需要 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>

【讨论】:

【参考方案23】:

有一种使用滚动行为的 css 方法。添加以下属性。

    scroll-behavior: smooth;

就是这样。无需 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:请检查浏览器兼容性。

【讨论】:

我应该对哪个容器使用滚动行为:平滑; 如有疑问,请将其添加到body标签@CraZyDroiD【参考方案24】:

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

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

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

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

【讨论】:

另外,当您从不同的 url 点击散列链接时需要考虑,因此会有很多 window.location....$(this).attr('href').substring(...) 一起处理【参考方案25】:

仅 CSS

html 
    scroll-behavior: smooth !important;

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

以编程方式:一些额外和高级的东西

// 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'
)

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

详细了解请阅读article

【讨论】:

【参考方案26】:

需要 jquery 和动画来锚定具有指定名称而不是 id 的标签,同时将哈希添加到浏览器 url。还修复了大多数 jquery 答案中的错误,其中 # 符号没有以转义反斜杠为前缀。不幸的是,后退按钮无法正确导航回以前的哈希链接...

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

【讨论】:

【参考方案27】:

对哈希 id 滚动的平滑滚动提供原生支持。

html 
  scroll-behavior: smooth;

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

【讨论】:

【参考方案28】:

好吧,解决方案取决于问题的类型,我使用 javascript animate 方法来单击按钮。我使用来自以下链接的代码作为导航栏

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

【讨论】:

以上是关于单击锚链接时平滑滚动的主要内容,如果未能解决你的问题,请参考以下文章

javascript 单击哈希链接时平滑滚动

单击锚链接时如何实现平滑滚动到不同页面上的部分?

Android Studio 如何在 LinearLayout 元素中实现锚链接?

如何使用 Aurelia 通过单击内部锚链接保持在同一页面上?

使用动画在滚动底部时平滑显示隐藏按钮

单击锚链接时淡入/淡出音乐