修改现有的jQuery以更改Scroll上的URL

我有一个从w3schools.com获得的jQuery代码,其中ON CLICK(单击 )更改了URL的#id,并且还允许平滑滚动到特定的DIV部分。 但它不适用于滚动。 我希望滚动效果相同。 当我向下或向上滚动到特定部分时,URL的#id应该更改。

当前的jQuery代码:

 $(document).ready(function(){ $("#navlist a").on('click', function(event) { if(this.hash !== ""){ var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 800, function(){ window.location.hash = hash; }); } }); }); 

我搜索了stackoverflow,我得到了这样的东西:

 $(document).bind('scroll',function(e){ $('div').each(function(){ if ($(this).offset().top  window.pageYOffset + 10){ window.location.hash = $(this).attr('id'); } }); }); 

这似乎工作,但当我放置代码时,其中一个代码正在停止执行另一个代码。 我想把两个代码组合成一个来实现onclick和滚动效果,但是我无法这样做(对jquery的弱手)。

具有ID的示例URL: http://localhost/sites/fh/index.php#first

请帮我开发。

您应该更改历史记录状态,而不是设置位置哈希。 这样您就可以避免浏览器强制页面滚动。 请查看以下内容:

 navlist = []; $("#navlist a").each(function(i) { var thisLink = $(this); var thisId = thisLink.attr('href'); var thisTarget = $(thisId); navlist.push({ 'anchor': thisLink, 'id': thisId, 'target': thisTarget }); thisLink.on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: thisTarget.offset().top }, 800); }); }); $(window).on('scroll resize', function(e) { $.each(navlist, function(e, elem) { var placement = elem.target[0].getBoundingClientRect(); if( placement.top0 ) { history.pushState({}, '', elem.id); console.log('Hash: ' + elem.id); return false; /* Exit $.each loop */ }; }); }); 
 nav a { display: block; } section { height: 600px; border-top: 1px solid black; } 
   
Section 1 Content
Section 2 Content
Section 3 Content