我有一个顶部标题是固定的,并在滚动上收缩。下面我有一个div元素(侧横幅),它必须在视图窗格中垂直居中,并且当我向下滚动时必须坚持到顶部标题。我不能让这个div元素停留在顶部的标题。
我试着使用CSS的位置:粘滞,但它不起作用。问题是侧栏横幅超过了滚动页的顶部标题。我还尝试添加了一个粘性类,它显示了一些javascript,但我一定是做错了什么,因为它不起作用。请帮帮我!
HTML:
<header id="topBanner">Top Banner</header>
<div class="content">
<div class="sideBanner" id="sideBanner">
</div>
</div>
CSS:
body{
margin: 0;
font-family: Arial, Helvetica, sans-serif;
background-color: #fcf2dc;
}
#topBanner {
background-color: #e9ab18;
padding: 50px 10px;
color: #000;
text-align: center;
font-size: 90px;
font-weight: bold;
position: fixed;
top: 0;
width: 100%;
transition: 0.2s;
}
.content {
position: relative;
height: 1000px;
}
.sideBanner {
position: absolute;
background: #f5d997;
width: 150px;
height: 400px;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
right: 10px;
}
.sticky {
position: fixed;
top: 0;
}
JAVASCRIPT:
// FUNCTION TO MAKE TOP HEADER SHRINK ON SCROLL:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 50 ||
document.documentElement.scrollTop > 50) {
document.getElementById("topBanner").style.fontSize = "30px";
} else {
document.getElementById("topBanner").style.fontSize = "90px";
}
}
发布于 2019-04-28 12:17:56
在您的HTML中没有类粘性。
您已经在CSS中创建了这个类,但是没有在HTML上应用这个类。
发布于 2019-04-28 12:26:09
你的粘性想法很好用。棘手的部分是知道它的top
值是什么。
在Chrome中的反复试验导致我将其设置为334px
,但您最好动态计算此值。您可以从topBanner.offsetHeight
开始,然后添加其他值(例如可能未包含在计算值中的填充或边距)。
我还在下面的代码片段中提供了topBanner z-index: 1
(它与您最初发布的内容几乎相同),以防止sideBanner在快速滚动时短暂地出现在它的前面。
(注意:在SO的全屏视图中,此代码片段的行为更加清晰。)
const topBanner = document.getElementById("topBanner");
const sideBanner = document.getElementById("sideBanner");
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
if (scrollTop > 50) {
topBanner.style.fontSize = "30px";
sideBanner.classList.add("sticky");
} else {
topBanner.style.fontSize = "90px";
sideBanner.classList.remove("sticky");
}
}
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
background-color: #fcf2dc;
}
#topBanner {
background-color: #e9ab18;
padding: 50px 10px;
color: #000;
text-align: center;
font-size: 90px;
font-weight: bold;
position: fixed;
top: 0;
width: 100%;
transition: 0.2s;
z-index: 1; /* Positions this element in front of others */
}
.content {
position: relative;
height: 1000px;
}
.sideBanner {
position: absolute;
background: f5d997;
width: 150px;
height: 400px;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
right: 10px;
}
.sticky {
position: fixed;
top: 334px; /* Hard-coded guess for this value, dynamic would be better */
}
<header id="topBanner">Top Banner</header>
<div class="content">
<div class="sideBanner" id="sideBanner">
s <br />
i <br />
d <br />
e <br />
<br />
b <br />
a <br />
n <br />
n <br />
e <br />
r <br />
</div>
</div>
https://stackoverflow.com/questions/55886701
复制相似问题