尝试平滑滚动,但出现JS错误

时间:2019-09-24 15:36:06

标签: javascript html css

首先,我不知道如何使用JS编程,但是我想在按下“ Trailer”按钮时制作平滑的滚动动画,但是会出现某种错误,指出:“ Uncaught ReferenceError:$ is未定义”。

有什么办法解决这个问题吗?

谢谢。

$('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
          };
        });
      }
    }
  });
.titulo { 
    list-style-type: none;
    text-decoration: none;
    font-family: "Source Sans Pro";
    text-transform: uppercase;
    text-align: center;
    color: #00000;
    font-size: 19px;
    font-weight: 700;
    letter-spacing: 2.5px;
    line-height: 22px;
    padding: 40px 0px 0px 0px;
  }
<ul>
  <li class="titulo"><a class="titulo" href="#trailer">TRAILER</a></li>
</ul>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
 
 <div id="trailer">
    <h1>TRAILER</h1>
</div>

2 个答案:

答案 0 :(得分:1)

您应该在项目中包含jQuery库。

只需将此标签放在html的<head></head>部分中即可。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

答案 1 :(得分:0)

如果您已经包含jQuery(请参阅其他注释),则可能是启用了jQuery的无冲突模式的情况。然后,您需要使用“ jQuery”而不是“ $”。