2017-10-22 17 views
-1

자바 스크립트에서 부드러운 스크롤 기능을 보았습니다.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를 사용하여 웹 사이트를 코딩했습니다. 어떻게 자바 스크립트 기능을 구현합니까? 나는 인터넷 검색을 해봤지만, 답변은 항상 완전히 새로운 것이 아니기 때문에 충분히 구체적인 것은 아닙니다.

도움을 많이 주시면 감사하겠습니다. 간단한 자바 스크립트에 대한

답변

1

당신의 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

+0

에 대해 "이 catch되지 않은 오류 ReferenceError : $은 정의되지 않았습니다. " 코드에 문제가 있습니까? –

+0

코드가 jQuery를 사용하기 때문에 - 예를 들어 $는 jQuery 구문이므로 - jQuery도 가져와야합니다. - 내 대답을 업데이트했습니다. – inxoy