如何使用Javascript平滑滚动?

时间:2017-10-22 17:54:11

标签: javascript html css scroll smoothing

我在JavaScript中遇到了一个平滑的滚动功能,如下所示。

// Select all links with hashes
$('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
          };
        });
      }
    }
  });

我目前有一个使用HTML和CSS编码的网站。 如何实现javascript函数?我试过谷歌搜索它,但答案总是不够明确,因为我真的很新。

非常感谢帮助!

1 个答案:

答案 0 :(得分:1)

对于简单的javascript,就像在html头中添加脚本标记一样简单

<head>
  <title>:D</title>
  ...
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    //your javascript here
  </script>
</head>

当然有更多方法可以实现这一目标 - 更多信息https://www.w3schools.com/js/js_whereto.asp