【问题标题】:sticky header on scroll with CSS issues滚动时出现 CSS 问题的粘性标题
【发布时间】:2014-01-11 21:49:01
【问题描述】:

我已经构建了一个粘性标题,当您滚动浏览导航区域时会显示该标题,并且一切正常,除了当我调整窗口大小时,粘性标题在我重新加载页面之前不会自动调整,即使宽度是 100% 并且位置是固定的。每个其他 div 都会自动调整,但不是这个(可能是因为 javascript 从固定标题中克隆了它?)。因此,我无法弄清楚如何修复的错误是当我更改窗口大小而不重新加载时使 .floatingHeader 自动调整。关于如何修复这个小的审美错误有什么想法吗?

我的 HTML:

 <div class="persist-area">
    <div class="top">
    <div class="persist-header">
         <div class="head">
            <div>
                <div class="home active" onClick="location.href='index.html'"></div>
                <a href="#">About</a><a href="#">Contact</a>

                <div class="home right"></div><a href="#" id="right">News</a>
            </div>
          </div>
    </div>
    </div>

CSS:

.floatingHeader {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    display: none;
    z-index: 99999;
}

还有 Javascript:

function UpdateTableHeaders() {
   $(".persist-area").each(function() {

       var el             = $(this),
           offset         = el.offset(),
           scrollTop      = $(window).scrollTop(),
           floatingHeader = $(".floatingHeader", this)

       if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
           floatingHeader.css({
            "display": "block"
           });
       } else {
           floatingHeader.css({
            "display": "none"
           });      
       };
   });
}

// DOM Ready      
$(function() {

   var clonedHeaderRow;

   $(".persist-area").each(function() {
       clonedHeaderRow = $(".persist-header", this);
       clonedHeaderRow
         .before(clonedHeaderRow.clone())
         .css("width", clonedHeaderRow.width())
         .addClass("floatingHeader");

   });

   $(window)
    .scroll(UpdateTableHeaders)
    .trigger("scroll");

});

【问题讨论】:

    标签: javascript css


    【解决方案1】:

    当浏览器构建 DOM 树时触发 DOM 就绪事件(因此所有元素都已被解析并放置在树中的正确位置)。但是此时 CSS 还没有被解析并应用于 DOM。因此,当您的 JavaScript 执行时,浏览器尚未将 width: 100% 应用到 .persist-header。因此,jQuery 只是默认返回元素的实际宽度(以像素为单位)。该值就是应用于克隆元素的值。

    如果您改为等待window.load,您的代码将按预期工作。 (嗯,克隆部分;我不能说其余的;^)

    【讨论】:

      【解决方案2】:

      您好,我遇到了完全相同的问题。我发现我需要“调整” JavaScript 事件的大小。我添加了这个功能,它对我有用。我希望这有帮助。

           $(document).ready(function () {        
            $(window).resize(function() {
            $(".floatingHeader").css("width",$(".persist-header").width());
          });
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 2016-04-30
        • 1970-01-01
        • 2016-01-14
        相关资源
        最近更新 更多