当元素用锚点动态包裹时,平滑滚动不起作用

Smooth scrolling nor working when element is dynamically wrapped with anchor

对于移动设备,我想将所有 h1 标题转换为可以平滑滚动到目标的锚点。为实现这一点,当某个设备发生调整大小时,我只是用 a 标签包装 h1 标签的内容,然后在设备返回时解开 a 标签的内容到桌面宽度。

$(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
  });
});


//the function to convert the heading to an anchor for devices smaller than 780px
function makeResponsive() {
  if ($(window).width() < 780) {
    if ($('a').length) {
      return true;
    } else {
      $('h1').each(function() {
        $(this).contents().eq(0).wrap('<a href="#section2"></a>');
      });
    }


  } else {
    $('a').contents().unwrap();
  }
}

//run on document load and on window resize
$(document).ready(function() {

  //on load
  makeResponsive()

  //on resize
  $(window).resize(function() {
    makeResponsive();
  });

});
body,
html,
.main {
  height: 100%;
}

section {
  min-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
  The Heading
</h1>

<div class="main">
  <section></section>
</div>

<div class="main" id="section2">
  <section style="background-color:blue"></section>
</div>

问题是,当 h1 内容转换为锚点时,平滑滚动根本没有发生,锚点只是跳转到目标。

与其将其包裹在锚点中,不如将 'mobile-anchor' class 添加到这些标题中。然后,不再监听对锚点的点击,而是监听对 'mobile-anchor' 的点击并更改:

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

或者更简单的解决方案 - 在您的点击功能结束之前,添加一个 'return false;' 这样浏览器就不会自行向下滚动页面。

编辑:此外,将所有内容包装在单个 documentReady 函数中并在添加点击侦听器之前执行 makeResponsive()。

您的 a-Tag 没有获得点击事件,因为您在它不存在时添加了侦听器。

试试这个

$(document).on('click', 'a', function(event) {...