简体   繁体   English

滚动到锚点

[英]Scroll to the anchor

Code: 码:

function scroll_page(){

        var target = document.location.hash.replace("#","");
        var selector = 'div[id='+target+']';
        alert(selector);
        $('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
        return false;
    };

Сode is called here: Сode在这里被称为:

$(window).on('hashchange', function() {
  scroll_page();
    });

The problem is that when you click on the link jumps sharply to this div , and then gently pulls up to its top . 问题是,当您单击链接时,该链接会急剧跳至该div,然后轻轻向上拉至其顶部。

Try the following code, 试试下面的代码,

$(function() {
      $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 140
        }, 1000);
        return false;
      }
    }
  });
});

If you have an anchor in your link like <a href='#id'> , then it will trigger before your JavaScript. 如果您的链接中有锚点,例如<a href='#id'> ,那么它将在您的JavaScript之前触发。 hashchange event occurs after the scrolling to the anchor. hashchange事件发生在滚动到锚点之后。

To prevent this, you need to bind to click event and prevent default behaviour. 为防止这种情况,您需要绑定到click事件并阻止默认行为。

I would do something like this. 我会做这样的事情。

HTML: HTML:

<a class="slow-scroll" href="#first">First</a>
<a class="slow-scroll" href="#second">First</a>
<a class="slow-scroll" href="#third">First</a>

JS: JS:

$(".slow-scroll").on('click', function(e) {
    var target = $(this).attr("href").substr(1);
    var selector = 'div[id='+target+']';
    alert(selector);
    $('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
    e.preventDefault();
    return false;
});

Here is the JSFiddle Demo . 这是JSFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM