我还添加了一个css转换,使其淡出,但这只是个人喜好的问题。如果你愿意的话,你可以把它去掉。
CODEPEN
css格式
#header {
display: flex;
justify-content: flex-end;
background: rgba(139, 139, 157, 0);
-webkit-transition: background 0.5s ease-in-out;
-moz-transition: background 0.5s ease-in-out;
-ms-transition: background 0.5s ease-in-out;
-o-transition: background 0.5s ease-in-out;
transition: background 0.5s ease-in-out;
z-index: 2;
position: fixed;
top: 0;
left: 0;
right: 0;
}
#header.isSticky {
background: rgb(139, 139, 157, 0.7);
-webkit-transition: background 0.5s ease-in-out;
-moz-transition: background 0.5s ease-in-out;
-ms-transition: background 0.5s ease-in-out;
-o-transition: background 0.5s ease-in-out;
transition: background 0.5s ease-in-out;
}
js公司
$(document).ready(function(){// checks vertical position of scroll bar
var scrollY = $(this).scrollTop();
// when user refreshes psge
if (scrollY > 0) {
// if it is anywhere but the top change opacity by adding class .isSticky
$('#header').addClass('isSticky');
} else {
$('#header').removeClass('isSticky');
}
$(window).on('scroll', function(){
// while uesr scrolls check the scrollTop position
var scrollY = $(this).scrollTop();
if (scrollY > 0) {
$('#header').addClass('isSticky');
} else {
$('#header').removeClass('isSticky');
}
});
});