如何在定义的体宽内保持粘性导航栏?

问题描述 投票:1回答:1

滚动时,我的粘性导航栏从体宽(最大1450px)变为100%屏幕宽度。 https://biogenity.com/RC19/index.html我用CSS定义了体宽:

    body {
      max-width: 1450px;
    }

对于粘性导航栏,我目前使用100%宽度,但它不适用于正文宽度。我不太确定要使用什么。

    .sticky.is-sticky {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        z-index: 1000;
        width: 100%;
    }

这可能是通过.js修复的吗?

            $(document).ready(function () {
            // Custom function which toggles between sticky class (is-sticky)
            var stickyToggle = function (sticky, stickyWrapper, scrollElement) {
                var stickyHeight = sticky.outerHeight();
                var stickyTop = stickyWrapper.offset().top;
                if (scrollElement.scrollTop() >= stickyTop) {
                    stickyWrapper.height(stickyHeight);
                    sticky.addClass("is-sticky");
                }
                else {
                    sticky.removeClass("is-sticky");
                    stickyWrapper.height('auto');
                }
            };

            // Find all data-toggle="sticky-onscroll" elements
            $('[data-toggle="sticky-onscroll"]').each(function () {
                var sticky = $(this);
                var stickyWrapper = $('<div>').addClass('sticky-wrapper'); // insert hidden element to maintain actual top offset on page
                sticky.before(stickyWrapper);
                sticky.addClass('sticky');

                // Scroll & resize events
                $(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function () {
                    stickyToggle(sticky, stickyWrapper, $(this));
                });

                // On page load
                stickyToggle(sticky, stickyWrapper, $(window));
            });
        });

提前致谢。

javascript html bootstrap-4 navbar
1个回答
0
投票

通过使用position:fixed,您可以从正常文档流中删除元素,因此我不相信正文样式适用。

来自position - CSS: Cascading Style Sheets | MDN

该元素将从普通文档流中删除,并且不会为页面布局中的元素创建空间。

因此,您应该为它设置最大宽度,并通过将leftright设置为auto来使其居中:

.sticky.is-sticky {
    position: fixed;
    max-width: 1450px;
    left: auto;
    right: auto;
    top: 0;
    z-index: 1000;
    width: 100%;
}
© www.soinside.com 2019 - 2024. All rights reserved.