简体   繁体   English

单击链接时禁用默认锚跳转

[英]Disable default anchor jumping when clicking on a link

I've searched hours and finally found a light jQuery code which allows me to animate the click of an anchor link, but when I click on one link it animates down and then jump 100px to the top without animation because the hash is given to the url after the animation which leads to the default anchor link behavior when you click it. 我搜索了几个小时,终于找到了一个简短的jQuery代码,该代码使我可以对锚链接的单击进行动画处理,但是当我单击一个链接时,它会向下动画,然后在没有动画的情况下跳至顶部100px,因为将哈希值赋予了动画后的url,当您单击它时会导致默认的锚链接行为。

I have a code sample for you with a little comment from me for a fix, or well I thought It'll be a fix... 我为您提供了一个代码示例,并提供了一些修正意见,或者我认为这将是一个修复...

// Scroll.js (https://css-tricks.com/snippets/jquery/smooth- 
scrolling/#comment-1635851)

/*
*   Scroll.js:
*   1. added -100 after the .top property which reflects the navigation height.
*/

$(document).ready(function(){

// Add smooth scrolling to all links
$('a').on('click', function(e) {

  // Make sure this.hash has a value before overriding default behavior
  if (this.hash !== "") {
    // Prevent default anchor click behavior
    e.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-100 // /* [1] */
    }, 800, function(){

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

}); });

Just write on the anchor href attribute javascript::void(0) as in 只需在锚href属性javascript::void(0)上编写即可

<a href="javascript:void(0)"></a>

Though if you want it to act as an anchor and have a url... this will not work :( 虽然如果您希望它充当锚并具有网址...这将不起作用:(

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

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