在锚点上平滑滚动

时间:2018-01-25 19:27:44

标签: javascript jquery html css

当我点击导航栏中的按钮时,我想添加一个平滑的滚动效果。 它跳转到链接但没有平滑的滚动效果

我的部分代码:

<section id="home"></section>

这是与之关联的按钮

<a class="nav-link" href="#home">home</a>

以下是我尝试的一些JS脚本,但没有一个工作

$(document).ready(function(){
// Add smooth scrolling to all links
$("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
  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 800, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
  });
} // End if

第二个

$(document).ready(function() {
    // check for hash when page has loaded
    if (getHash() != null) {
        checkForScrolling();
    }
});

// listen for hash change event here
window.onhashchange = function() {
    checkForScrolling();
};

// return hash if so or null if hash is empty
function getHash() {
    var hash = window.location.hash.replace('#', '');
    if (hash != '') {
        return hash;
    } else {
        return null;
    }
}

// this function handles your scrolling
function checkForScrolling() {
    // first get your element by attribute selector
    var elem = $('[data-anchor="' + getHash() + '"]');

    // cheeck if element exists
    if (elem.length > 0) {
        $('html, body').stop().animate({
            scrollTop: elem.offset().top
        }, 300);
    }
}

4 个答案:

答案 0 :(得分:2)

有趣的是,这不是调试代码的请求,这里是working example

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

,说明为here

答案 1 :(得分:2)

您在}); } // End if部分之后忘记了右括号。 因此,如果您将此}); });粘贴到第一个底部,它将正常工作。

完成的代码如下所示:

$(document).ready(function(){
// Add smooth scrolling to all links
$("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
  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 800, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
  });
} // End if 
});
});

答案 2 :(得分:2)

尝试使用id获取scrollTop值,然后将offset().top值设置为特定ID animate(),并使用click平滑滚动{{1} 1}}

Stack Snippet

&#13;
&#13;
$(document).on("click", ".nav-link", function(e) {
  e.preventDefault();

  var hash = $(this).attr("href");
  if ($(hash).length === 0) {
    return;
  }
  //console.log($(hash).offset().top)
  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 800)
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="nav-link" href="#home">home</a>
<a class="nav-link" href="#about">about</a>
<div class="other-section">
  other-section<br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
</div>
<section id="home">
  <h1>Home</h1>
</section>
<div class="other-section">
  other-section<br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
  <br> other-section
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:2)

&#13;
&#13;
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('mouseover', 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
  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 800, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
  });
} // End if 
});
});
&#13;
body, html, .main {
    height: 100%;
}

section {
    width:80%;
    height:80%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">


<section id="home">HOME
<br><a class="nav-link" href="#myAnchor">go2end</a>    

    </section>
<div class="main">    
<section style="background-color:blue"></secion>
</div>
<a id="myAnchor" class="nav-link" href="#home">home</a>
&#13;
&#13;
&#13;

正在滚动的是页面,所以为了最好地引用它,在使用jQuery时需要这段代码:

$('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

@ bru02 的修正是精明的,因此我使用该代码来演示平滑的滚动效果。但是,我更改了代码,以便用户只需将鼠标悬停在链接上而不是点击它 - 更便于保存手腕。并且,提供HTML以便人们也可以向上或向下滚动页面。

脚本本身显然来自here,也在那里工作。 OP引用的脚本由于复制/粘贴不完整而失败。