製作部分堅持頂部我試圖創建一個頁面,當每個部分到達窗口的頂部,它將添加一個粘性類到元素,它將固定到頁面的頂部。通過添加類
我試圖讓最終的結果看起來像一堆是來和留在窗口
頂頁這是到目前爲止我的代碼: -
$(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。 –