gpt4 book ai didi

javascript - 使固定的顶部元素随页面滚动(一旦内容到达它)

转载 作者:行者123 更新时间:2023-11-28 12:34:51 25 4
gpt4 key购买 nike

所有页面内容(红色“测试” 在我的图片中)应该放在顶部 100%(应该开始滚动才能看到它)

顶部的Header(在我的图片中用黑色标记)应该固定在页面顶部。
一旦内容到达标题,它就应该开始与其余内容一起滚动。

Visual Representation

(我不知道从哪里开始解决这个问题...没有 JavaScript 可以完成吗?)
预先感谢大家的帮助。

最佳答案

我用几行 JS 代码想出了一个绝招:

jsBin live demo

var heaF = document.getElementById("headerFixed");
var heaC = document.getElementById("headerClone");

heaC.innerHTML = heaF.innerHTML; // Clone header content (SEO wise)

function hero(){
var t = heaC.getBoundingClientRect().top; // Keep track of the clone top pos.
heaF.style.opacity = t<0 ? 0 : 1; // Toggle Org header opacity
heaC.style.opacity = t<0 ? 1 : 0; // Toggle Clone header opacity
}

hero(); // Do it when DOM is read
window.onscroll = hero; // Do it on scroll
window.onresize = hero; // But also on rresize

逻辑:

      +--  +----------------+-- (Viewport Top)
| | headerFixed | opacity:1; 0 when the Clone hits Viewp.Top
h +----------------+
e | |
r | |
o +----------------+
| # headerClone | opacity:0; 1 when it hits Viewp.Top
+-- +----------------+-- (Viewport Bottom)
| Content... |
⋮ ⋮

HTML:

<div id="hero">
<div id="headerFixed"><h1>Header</h1></div>
<div id="headerClone"></div>
</div>
<div id="content">Website template and content here</div>

CSS:

html, body { height:100%; }
#hero{ // This guy contains header and the JS cloned header
height:100%; // In order to cover the whole viewport height
}
#headerFixed {
position: fixed; // Will be always fixed!
width: 100%;
}
#headerClone{
position:absolute;
bottom:0; // Place it at the bottom
opacity:0; // (Uncomment this line to see it in action)
width:100%;
}

提示:如果以上内容不清楚,请为我们所有的元素添加不同的背景色。你最好看看会发生什么。

关于javascript - 使固定的顶部元素随页面滚动(一旦内容到达它),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956266/

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