【问题标题】:Smooth scrolling nor working when element is dynamically wrapped with anchor当元素被锚点动态包裹时,平滑滚动不起作用
【发布时间】:2017-04-04 13:54:33
【问题描述】:

对于移动设备,我想将所有 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内容转换为anchor时,根本没有平滑滚动,anchor只是跳转到目标。

【问题讨论】:

    标签: javascript jquery responsive smooth-scrolling


    【解决方案1】:

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

    试试这个

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

    【讨论】:

      【解决方案2】:

      无需将其包装在锚点中,只需将“mobile-anchor”类添加到这些标题中即可。然后,不要监听锚点的点击,而是监听“mobile-anchor”的点击并更改:

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

      或者甚至更简单的解决方案 - 在您的点击功能结束之前,添加一个“return false;”所以浏览器不会自己向下滚动页面。

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

      【讨论】:

        猜你喜欢
        • 2017-03-15
        • 1970-01-01
        • 1970-01-01
        • 2014-12-19
        • 1970-01-01
        • 1970-01-01
        • 2019-05-05
        • 1970-01-01
        相关资源
        最近更新 更多