javascript - 如何在窗口调整大小时更新粘性菜单的 CSS 定位

标签 javascript jquery css

我基于 an example from W3 schools 构建了一个粘性导航栏。它工作得很好 - 除了当我调整窗口大小时,导航菜单与页面内容的对齐不正确。

您会看到我有一些代码,通过检查页面上的另一个元素来找到菜单左侧的正确偏移量。然后添加一些左侧填充以正确对齐。 (如果没有这个,position:fixed 值只会将粘性导航发送到页面的最左侧)。

这在滚动上效果很好!但是,如果水平调整窗口大小,则左侧填充值不会更新。

我已经尝试了 $(window).resize 的几次迭代,但未能使其正常工作。我确信这是一行简单的代码,我只是不明白。提前致谢!

setTimeout(function () { 
    // When the user scrolls the page, execute myFunction
    window.onscroll = function() {myFunction()};

    // Get the navbar
    var navbar = document.getElementById("app");

    // Get the offset position of the navbar
    var sticky = $("#app").offset().top

    // Find correct offset for left side of menu (by checking #title element)
    var element = document.getElementById('title');
    var leftPos = element.getBoundingClientRect().left + window.scrollX;
    var roundLeft = (Math.round(leftPos)) - 5;

    // Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
    function myFunction() {
      if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky")
        navbar.style.cssText = "padding-left:" + roundLeft + "px!important";    

      } else {
        navbar.classList.remove("sticky");
        navbar.style.cssText = "padding-left:inherit";
      }
    }

}, 4000);
.sticky {
    position: fixed;
    top: 0;
    width: 100%;
    background: rgba(255, 255, 255, 0.99);
    z-index: 9 !important;
    max-width: none !important;
    box-shadow: 0px 1px 10px #999;
}

(我使用 setTimeout 因为我们的 Shiny 应用需要几秒钟的时间来加载和填充内容。)

最佳答案

您应该使用带有 position: Sticky 的纯 CSS 解决方案

它确实具有可接受的浏览器支持百分比: https://caniuse.com/#feat=css-sticky

由于这只是样式,因此在旧浏览器中将其显示为静态可能没问题。

关于javascript - 如何在窗口调整大小时更新粘性菜单的 CSS 定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61602013/

相关文章:

html - CSS 变换比例滚动问题

javascript - 在使用 angular + .net Core 开发应用程序时,我应该将资源放在哪里

javascript - 为什么 JavaScript 的 setTimeout 不减慢 keydown 率?

javascript - 如何对动态添加数据属性的div进行排序,而不重新组织具有相同数据属性的现有div

jquery - 使用 jQuery 获取鼠标单击图像的 X/Y 坐标

边框弄乱了 HTML 宽度

javascript - SlideShow 悬停在左侧,向右移动图像

javascript - 垫子单选按钮颜色的 Angular 变化

javascript - 组件卸载后如何调用函数?

javascript - 如何使用 D3(或只是 javascript)将表单选项设置为 "selected"