jQuery在向下滚动页面时更改哈希(片段标识符)

我正在建立一个寻呼机网站。 例如。 每个页面(总共5个)位于一个大页面上,主菜单固定在顶部。 当您单击菜单链接时,它会将您向下滑动到该页面锚标记,并且单击的菜单项将获得“活动”CSS类。

我现在要做的是允许用户滚动自己,但仍然有菜单“活动”项和URL哈希更改。

所以我的问题基本上是如何知道用户何时向下滚动到不同的页面,以便我可以更新菜单和URL哈希(片段标识符)。

谢谢

它可能但你的页面有一个要求(我的解决方案):

你的页面必须用div(或任何部分)用独特的id分隔(我希望你不要使用anchor 的)

比你可以使用这样的代码:

 $(document).bind('scroll',function(e){ $('section').each(function(){ if ( $(this).offset().top < window.pageYOffset + 10 //begins before top && $(this).offset().top + $(this).height() > window.pageYOffset + 10 //but ends in visible area //+ 10 allows you to change hash before it hits the top border ) { window.location.hash = $(this).attr('id'); } }); }); 

用这样的HTML

 
Home
Works
About

我有相同的修复高度部分内容的问题,这将根据滚动更改哈希。这样的代码在Chrome的其他浏览器上不起作用。 并且还在滚动中操纵DOM然后它需要花费很长时间才能获得该事件参考http://www.smashingmagazine.com/2013/06/10/pinterest-paint-performance-case-study/这里有样本我如何解决这个问题的代码

  (function () { // Find all top,bottom and Hash of each sections, // Do this only if the section height remain the same always // Move this into the step() if your section height does change. // eg browser resize // var section = $.map($("section"), function (e) { var $e = $(e); var pos = $e.position(); return { top: pos.top, bottom: pos.top + $e.height(), hash: $e.attr('id') }; }); //Checking scroll var top = null; var changed = false; var currentHash = null; $(window).scroll(function () { var newTop = $(document).scrollTop(); changed = newTop != top; if (changed) { top = newTop; } }); // You wouldn't want to keep checking the scroll state as // it affects the browser performance when it's accessing // DOM and reduce your FPS (Frame per Seconds) for scrolling // function step() { if (!changed) { // Top did not change return setTimeout(step, 200); } var count = section.length; var p; while (p = section[--count]) { if (p.top >= top || p.bottom <= top) { continue; } if (currentHash == p.hash) { break; } var scrollTop = $(document).scrollTop(); window.location.hash = currentHash = p.hash; // prevent browser to scroll $(document).scrollTop(scrollTop); } setTimeout(step, 200); } setTimeout(step, 200); })(); 

演示

您正在寻找.scroll()事件处理程序

使用jquery,您可以使用scrollTop方法查找滚动位置,然后将其与页面上元素的位置进行比较,以确定它们在页面上的位置并相应地更新。