【问题标题】:Window resizing problem to detect anchor point窗口大小调整问题以检测锚点
【发布时间】:2018-09-21 15:42:36
【问题描述】:

在我的 HTML 页面上,我有多个部分创建垂直滚动效果。这些部分中的每一个都具有屏幕窗口的 100% 的宽度和高度。在页面顶部,我还有一个设置为position: fixed 的菜单。当固定菜单到达并通过滚动页面检测到锚点时,菜单的文本颜色会发生变化。

我的问题是当我调整浏览器窗口的大小时,我失去了对锚点的检测。因此,当菜单滚动时,将锚点悬停在菜单颜色不会改变。

<header id="masthead" class="site-header"> Menu text </header>

<section id="section-1" class="hero"> Section 1 </section>
<section id="section-2" class="hero"> Section 2 </section>

<div class="anchor switch-menu-color"></div>

<section id="section-3" class="hero"> Section 3 </section>
<section id="section-4" class="hero"> Section 4 </section>
var anchor = $('.switch-menu-color').offset().top - 40,
  $window = $(window);

$window.on('load scroll resize', function() {
  if ($window.scrollTop() >= anchor) {
    $("#masthead").addClass("black-text");
  } else {
    $("#masthead").removeClass("black-text");
  }
});

感谢您的帮助!

【问题讨论】:

    标签: jquery scroll resize anchor detect


    【解决方案1】:

    问题是因为您只在页面加载时读取了.switch-menu-color 元素的offset()。您还需要在调整页面大小时执行此操作,如下所示:

    var anchor = $('.switch-menu-color').offset().top - 40,
      $window = $(window);
    
    $window.on({
      'load scroll': setLinkColour,
      'resize': function() {
        anchor = $('.switch-menu-color').offset().top - 40;
        setLinkColour();
      }
    });
    
    function setLinkColour() {
      $('#masthead').toggleClass('black-text', $window.scrollTop() >= anchor);
    } 
    

    请注意,出于性能原因,我将load scrollresize 事件分开。滚动页面时无需重新计算offset(),只需调整大小即可。

    还要注意 toggleClass() 与布尔参数的使用,以使代码更简洁。

    【讨论】:

    • 感谢 Rory 的回答,我确实理解您编写的代码。但是,它仍然存在同样的问题。当我调整窗口大小时,锚点在页面加载时保持相同的位置。
    猜你喜欢
    • 2013-02-10
    • 2011-09-26
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多