gpt4 book ai didi

javascript - 将 div 粘贴到滚动顶部并稍后取消粘贴

转载 作者:行者123 更新时间:2023-12-02 22:45:28 28 4
gpt4 key购买 nike

目前,当 div 到达浏览器顶部时,它会变得粘性(固定),并且效果完美。我想要的是在继续滚动另外 500 像素后,div 再次松开。

有办法做到这一点吗?

ps。我知道 Stickem 解决方案,但如果使用 Javascript,那就太多了,我感觉这可以更容易完成。

window.onscroll = function() {myFunction()};
var header = document.getElementById("center");
var sticky = header.offsetTop-10;
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
#top { height:200px; background:#BFBDC1; }
#center { height:30px; background:#37323E; }
#bottom { height:4000px; background:#6D6A75; }

.sticky { position:fixed; top:0px; width:100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div id="top"></div>
<div id="center"></div>
<div id="bottom"></div>

最佳答案

只需为 if 条件添加一个上限就可以解决问题。

不仅检查当前偏移量是否大于下限(在本例中为 sticky),还要检查它是否小于所需的上限(sticky + 500)。

window.onscroll = function() {myFunction()};
var header = document.getElementById("center");
var sticky = header.offsetTop-10;
function myFunction() {
if (window.pageYOffset > sticky && window.pageYOffset < sticky + 500) { // <--here
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
#top { height:200px; background:#BFBDC1; }
#center { height:30px; background:#37323E; }
#bottom { height:4000px; background:#6D6A75; }

.sticky { position:fixed; top:0px; width:100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div id="top"></div>
<div id="center"></div>
<div id="bottom"></div>

关于javascript - 将 div 粘贴到滚动顶部并稍后取消粘贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58421219/

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