gpt4 book ai didi

javascript - 到达顶部后div的宽度发生变化

转载 作者:行者123 更新时间:2023-11-28 14:38:23 25 4
gpt4 key购买 nike

我正在制作一个博客站点示例 我想在 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 得到了修复,但是 div 的宽度发生了变化并且它被缩小了。
我不知道为什么会发生这种情况,从过去 2 天开始我就一直坚持这一点。

可以看例子Here

最佳答案

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

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

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

编辑

固定

The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block established by the viewport, except when one of its ancestors has a transform, perspective, or filter property set to something other than none (see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) Its final position is determined by the values of top, right, bottom, and left. This value always creates a new stacking context. In printed documents, the element is placed in the same position on every page.

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

关于javascript - 到达顶部后div的宽度发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com