首页 > 解决方案 > 到达顶部后 div 的宽度发生变化

问题描述

我正在制作一个博客网站示例,我想在 div 到达页面顶部后修复它的位置。我正在使用 materialize.css
这是我的代码

 <div class="row">
     <div class="col m8 s12">
     <!-- some content here -->
     </div>

    <div class="col s12 m4">
                    <div class="collection with-header" style="margin-top:3rem;">
                        <h5 class="collection-item">Trending topics</h5>
                        <a href="#" class="collection-item">Web design</a>
                        <a href="#" class="collection-item">Express framework</a>
                        <a href="#" class="collection-item">Cache API</a>
                        <a href="#" class="collection-item">Event handling in JavaScript</a>
                        <a href="#" class="collection-item">Django framework</a>
                    </div>

    <!-- This div should be fixed after reaching the top -->
                    <div class="card-panel center" id="post-author" style="width:auto">
                        <div class="follow-author">
                            <img src="https://source.unsplash.com/random/200x200" alt="" class="responsive-img circle"
                                style="width:75px;">
                            <div class="blue-text darken-3">Ishaan Sheikh</div>
                            <small class="grey-text">@sheikh_i</small>
                            <div class="divider" style="margin:1rem 0;"></div>
                            <div class="grey-text">Follow Author </div>
                            <a href="#"><i class="fab fa-facebook"></i></a>
                            <a href="#"><i class="fab fa-twitter"></i></a>
                            <a href="#"><i class="fab fa-instagram"></i></a>
                            <a href="#"><i class="fab fa-github"></i></a>
                         </div>
                    </div>
     </div>
 </div>

这是javascript代码。

window.onscroll = function () {
            myFunction();
        };

        var header = document.getElementById("post-author");
        var sticky = header.offsetTop;

        function myFunction() {
            if (window.pageYOffset > sticky) {
                header.classList.add("sticky");
            } else {
                header.classList.remove("sticky");
            }
        }

粘性类定义为:

.sticky {
            position: fixed;
            top: 0;
        }

问题是 div 得到修复,但width of the div changes and it gets shrinked.
我不知道为什么会发生这种情况,我从过去 2 天开始就被这个问题困扰着。

您可以在此处查看示例

标签: javascripthtmlcss

解决方案


您的问题是添加了sticky包含该position: fixed;属性的类。

fixed因此,有效地从列中删除了 div,width:auto现在的工作方式有所不同。

您需要使用固定宽度重新设计列

编辑

固定的

该元素会从正常的文档流中移除,并且不会在页面布局中为该元素创建空间。它相对于视口建立的初始包含块定位,除非它的祖先之一的变换、透视或过滤器属性设置为非无(请参阅 CSS 变换规范),在这种情况下,祖先表现为包含块。(请注意,浏览器与透视和过滤器的不一致会导致包含块的形成。)其最终位置由顶部、右侧、底部和左侧的值确定。此值始终创建一个新的堆叠上下文。在打印的文档中,元素放置在每一页的相同位置。

https://developer.mozilla.org/en-US/docs/Web/CSS/position


推荐阅读