这是我通过 CodePen 进行的精简版本:https://codepen.io/moosearch/pen/EaxYjEP
我正在尝试根据此图像实现两列布局:https://imgur.com/a/bj1tWCK
左栏是菜单侧边栏;右栏包含主要内容。主要内容块有一个水平横幅,代表我所在部门的品牌。横幅由两个 SVG 组成;一个是水平条纹背景,另一个是位于背景 SVG 上的徽标。如果用户向下滚动,横幅将部分隐藏 - 仅显示底部,徽标消失。如果用户向上滚动,它将完整显示横幅。
问题:当滚动回到页面顶部时,动作并不平滑 - 它分两次进行,而不是一次平滑的动作。
最近,两步运动让我抓狂不已,我不知道到底是什么原因造成的。如果不是因为这个原因,我的实现还是令人满意的。
相关代码...
HTML:
<div class="sidebar nav navbar flex-shrink-0" style="width: 280px">
<!-- sidebar... -->
</div>
<!-- This is for inserting the contents of the page -->
<main id="main-content-block" style="margin-top: -10px;">
<div id="banner-wrapper" class="banner-wrapper">
<div id="org-banner" class="banner">
<svg width="3000" height="130" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="3000" height="80" fill="red" />
<rect x="0" y="80" width="3000" height="25" fill="orange" />
<rect x="0" y="105" width="3000" height="25" fill="coral" />
</svg>
</div>
<div id="crest-container">
<div class="crestbg">
<svg width="125" height="125" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="125" height="125" fill="maroon" />
</svg>
</div>
</div>
</div>
<!-- Content -->
<hr>
</main>
样式表:
/* Note: I also use bootstrap.css styling, v5.3.3 */
body {
font-family: "Roboto";
display: flex;
flex-direction: row;
height: 100vh;
}
main {
height: 100vh;
flex-grow: 1;
overflow-y: auto;
padding: 10px 10px 10px 10px;
}
/* For banner */
#banner-wrapper {
position: sticky;
top: 0;
z-index: 10;
margin: -8px -10px 30px -10px;
height: 130px;
overflow: hidden;
transition: all 0.5s ease-out;
}
.banner svg {
height: 130px;
top: 0px;
}
/* Positions the crest within the banner BG. */
.crestbg svg {
height: 130px;
position: absolute;
top: 0px;
right: 40px;
}
.banner a {
text-decoration: none;
}
/* CSS for hiding banner partially when scrolling */
header {
height: 80px;
transition: all 0.5s ease-out;
}
header.scrolled {
height: 50px;
}
#banner-wrapper.scrolled {
top: -80px;
}
#crest-container.scrolled {
display: none;
}
詹姆斯:
// For banner scrolling.
const mainContentEle = document.getElementById('main-content-block')
mainContentEle.addEventListener('scroll', () => {
// Dependent on the SG banner dimensions and how it's designed. Change this as needed.
const scrollPixelCutoffValue = 80;
const headerElement = document.querySelector('header')
const svgBannerContainer = document.getElementById('banner-wrapper')
const crestContainer = document.getElementById('crest-container')
if (mainContentEle.scrollTop > scrollPixelCutoffValue) { // Adjust this value as needed
svgBannerContainer.classList.add('scrolled');
headerElement.classList.add('scrolled');
crestContainer.classList.add('scrolled');
} else {
svgBannerContainer.classList.remove('scrolled');
headerElement.classList.remove('scrolled');
crestContainer.classList.remove('scrolled');
}
return;
});
编辑:如果所选答案中的 JSFiddle 将来消失,我添加了自己的 CodePen 以供参考:https ://codepen.io/moosearch/pen/wBvwyxx