这节课我们将实现,当页面滚动的时候,导航栏不会消失,仍然出现在头部;
● 首先我们先添加一个新的class
.sticky {
position: fixed;
top: 0;
bottom: 0;
width: 100%;
background-color: #fff;
}
“position: fixed” 是 CSS 中的一个属性,用于控制元素的定位方式。当一个元素被设置为 “position: fixed” 时,它的位置将相对于浏览器窗口而不是文档流中的其他元素进行定位。这意味着即使页面滚动,该元素的位置也不会改变。
通常,“position: fixed” 属性用于创建固定在页面顶部或底部的导航栏、工具栏或广告等元素。由于这些元素需要保持在页面的相同位置,不受页面滚动的影响,因此使用 “position: fixed” 可以很方便地实现这个效果。
● 之后将这个新的类给到header上
● 这样当我们滚动的时候导航栏就会被固定
● 但是还是有一个层叠的问题
.sticky {
position: fixed;
top: 0;
bottom: 0;
width: 100%;
background-color: rgba(255, 255, 255, 0.97);
z-index: 999;
}
我们通过这个来改变层叠的效果:
“z-index: 999” 是 CSS 中的一个属性,用于控制元素的层叠顺序。当一个元素被设置为具有较高的 z-index 值时,它将显示在其他元素的上方。
具体来说,z-index 值越高的元素将显示在 z-index 值较低的元素的上方。如果两个元素具有相同的 z-index 值,则它们将按照它们在 HTML 中的出现顺序进行层叠。
在这种情况下,“z-index: 999” 表示该元素应该在其他具有较低 z-index 值的元素上方显示。这通常用于确保一个元素(例如导航栏)始终显示在其他元素(例如页面内容)的上方,以便用户可以轻松地访问该元素。
● 之后我们再给一下首页的缺少部分
.sticky {
position: fixed;
top: 0;
bottom: 0;
width: 100%;
height: 8rem;
padding-top: 0;
padding-bottom: 0;
background-color: rgba(255, 255, 255, 0.97);
z-index: 999;
box-shadow: 0 1.2rem 3.2rem rgba(0, 0, 0, 0.03);
}
● 但是这个并不是我们想要的粘性导航,我们想离开主页的时候出现粘性,否则不出现,这个我们需要通过js去实现
const sectionHeroEl = document.querySelector(".section-hero");
#这一行代码使用了document.querySelector方法来获取class为section-hero的元素并将其赋值给sectionHeroEl变量。
const obs = new IntersectionObserver(
function (entries) {
const ent = entries[0];
if (ent.isIntersecting == false) {
console.log(ent);
document.querySelector(".header").classList.add("sticky");
}
},
{
root: null,
threshold: 0,
}
);
##这一行代码创建了一个新的IntersectionObserver实例并将其赋值给obs变量。IntersectionObserver是一个用于监测元素与视窗交叉的API。在这个例子中,我们使用IntersectionObserver来监测当.section-hero元素不再可见时,将.header元素添加一个class为sticky。
obs.observe(sectionHeroEl);
● 但是当离开hero页面的时候,粘性导航处跳一下,我们来修复一下
.sticky .header{
position: fixed;
top: 0;
bottom: 0;
width: 100%;
height: 8rem;
padding-top: 0;
padding-bottom: 0;
background-color: rgba(255, 255, 255, 0.97);
z-index: 999;
box-shadow: 0 1.2rem 3.2rem rgba(0, 0, 0, 0.03);
}
.sticky .section-hero {
margin-top: 9.6rem;
}
const sectionHeroEl = document.querySelector(".section-hero");
const obs = new IntersectionObserver(
function (entries) {
const ent = entries[0];
if (ent.isIntersecting == false) {
console.log(ent);
document.body.classList.add("sticky");
}
},
{
root: null,
threshold: 0,
}
);
obs.observe(sectionHeroEl);
● 现在还有一个问题,当我们回到hero页面的时候,粘性导航依然存在,通过if语句即可解决
const sectionHeroEl = document.querySelector(".section-hero");
const obs = new IntersectionObserver(
function (entries) {
const ent = entries[0];
if (ent.isIntersecting == false) {
console.log(ent);
document.body.classList.add("sticky");
}
if (ent.isIntersecting == true) {
console.log(ent);
document.body.classList.remove("sticky");
}
},
{
root: null,
threshold: 0,
rootMargin: "-80px",
}
);
obs.observe(sectionHeroEl);