Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/90.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为Javascript使用平滑滚动?_Javascript_Html_Css_Scroll_Smoothing - Fatal编程技术网

如何为Javascript使用平滑滚动?

如何为Javascript使用平滑滚动?,javascript,html,css,scroll,smoothing,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

我遇到了一个来自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函数?我试过用谷歌搜索,但答案总是不够具体,因为我在这方面还真是新手


非常感谢您的帮助

对于简单的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>

:D
...
//你的javascript在这里

当然,有更多的方法可以实现这一点-有关更多信息,它会给出一个错误“uncaughtreferenceerror:$未定义”代码是否有问题?这是因为代码使用jQuery-例如$是jQuery语法-因此您也需要导入jQuery-我更新了我的答案