【问题标题】:Disable default anchor jumping when clicking on a link单击链接时禁用默认锚点跳转
【发布时间】:2019-02-01 10:38:30
【问题描述】:

我已经搜索了几个小时,终于找到了一个轻量级的 jQuery 代码,它允许我对锚链接的点击进行动画处理,但是当我点击一个链接时,它会向下动画,然后在没有动画的情况下跳到顶部 100px,因为哈希是在动画之后赋予 url,当您单击它时会导致默认的锚链接行为。

我有一个代码示例给你,我有一点评论来修复,或者我认为这将是一个修复......

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

});

【问题讨论】:

    标签: javascript jquery hash scroll offset


    【解决方案1】:

    只需在锚href属性javascript::void(0)上写

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

    虽然如果你想让它作为一个锚点并有一个 url ......这是行不通的 :(

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2021-07-30
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      相关资源
      最近更新 更多