制作部分坚持顶部我试图创建一个页面,当每个部分到达窗口的顶部,它将添加一个粘性类到元素,它将固定到页面的顶部。通过添加类
我试图让最终的结果看起来像一堆是来和留在窗口
顶页这是到目前为止我的代码: -
$(document).ready(function(){
var stickyTopSection = $('.home, .about, .gallery, .contact').offset().top;
var stickyTop = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyTopSection) {
$(this).addClass('sticky');
} else {
$(this).removeClass('sticky');
}
};
stickyTop();
$(window).scroll(function() {
stickyTop();
});
});
.home, .about, .gallery, .contact{
height: 100vh;
width: 100%;
}
.sticky{
position: fixed;
top: 0;
left: 0;
}
.home{
z-index: 1;
background-color: #fff;
}
.about{
z-index: 2;
background-color: #eee;
}
.gallery{
z-index: 3;
background-color: #ddd;
}
.contact{
z-index: 4;
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<header id="home" class="home">
<h1>Welcome</h1>
</header>
<section id="about" class="about">
<h2>About</h2>
</section>
<section id="gallery" class="gallery">
<h2>Gallery</h2>
</section>
<section id="contact" class="contact">
<h2>Contact</h2>
</section>
当我使用“位置:粘”,我检查元素说,它的一个无效的属性值 – Jason
@Jason你可能使用的浏览器不支持此功能(你可以用caniuse检查链接我提供),你可以在这种情况下使用polyfill。 –