繁体   English   中英

使用 jQuery 滚动到锚点仅在您不在当前页面上时才有效

[英]Scroll to anchor with jQuery only works when your not on the current page

问题是,当我单击具有同一页面上的主题标签的链接时,动画滚动不起作用。 动画滚动仅在您不在当前页面时有效。

网址看起来像这样:

  • website.com/about#people,
  • website.com/about#contact

因此,假设您在“关于页面”上并单击其中任何一个链接,向下滚动动画将不起作用,但假设您在主页上并单击这些链接中的任何一个,动画确实有效。

不幸的是,我无法在代码片段上复制该问题,但我使用的是相同的js代码。 奇怪的是,在此代码段中,即使您在同一页面上,动画也能正常工作。 不,我在控制台上没有收到任何错误。

谢谢!

 $('nav a[href^="#"]').click(function(){ $('html, body').animate({ scrollTop: $(this.hash).offset().top }, 400); return false; });
 #topSection{ background: red; height: 400px; } #middleSection{ background: blue; height: 400px; } #lastSection{ background: black; height: 400px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <ul> <li><a href="#topSection">Top Section</a></li> <li><a href="#middleSection">Middle Section</a></li> <li><a href="#lastSection">Last Section</a></li> </ul> </nav> <div id="topSection"> </div> <div id="middleSection"> </div> <div id="lastSection"> </div>

当您访问带有散列的页面时,滚动到散列不起作用的原因是您的代码仅在单击链接时调用。 为了进一步详细说明我的评论,因此您还需要在加载页面时调用相同的代码。

这可以通过简单地将点击处理程序中的所有逻辑抽象成一个可以独立于点击事件调用的函数来完成:

function smoothScrollTo(hash) {
  if (!hash)
    return;

  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 400);
}

$(function() {
  // Smooth scrolling when the page is loaded
  smoothScrollTo(window.location.hash);

  // Smooth scrolling when a link is clicked
  $('nav a[href^="#"]').click(function() {
    smoothScrollTo(this.hash)
    return false;
  });
});

请参阅下面的概念验证:

 function smoothScrollTo(hash) { if (!hash) return; $('html, body').animate({ scrollTop: $(hash).offset().top }, 400); } $(function() { // Smooth scrolling when the page is loaded smoothScrollTo(window.location.hash); // Smooth scrolling when a link is clicked $('nav a[href^="#"]').click(function() { smoothScrollTo(this.hash) return false; }); });
 #topSection { background: red; height: 400px; } #middleSection { background: blue; height: 400px; } #lastSection { background: black; height: 400px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <ul> <li><a href="#topSection">Top Section</a></li> <li><a href="#middleSection">Middle Section</a></li> <li><a href="#lastSection">Last Section</a></li> </ul> </nav> <div id="topSection"> </div> <div id="middleSection"> </div> <div id="lastSection"> </div>

暂无
暂无

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

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