答案 0 :(得分:1)
希望这可以帮助你。
<style>
/* Initial Styling Applied Here */
header{
}
/* Wanted Styling While Fixed */
header.fixed{
position:fixed;
top:0;
z-index:100;
}
</style>
用HTML创建标题(这可以是任何容器,真的)
<header></header>
在JS / jQuery中创建事件处理程序
<script>
// On Scroll
$(window).scroll(function(){
// If we have scrolled more than 10px
if($(document).scrollTop() > 10){
// Add class "fixed" to header element
$('header').addClass('fixed');
// Otherwise
}else{
// If header already has "fixed" class
if($('header').hasClass('fixed')){
// Remove said class
$('header').removeClass('fixed');
}
}
});
</script>
答案 1 :(得分:0)
使用Bootstrap affix
组件在页面滚动时更改导航栏样式。
<div class="navbar navbar-default navbar-fixed-top" data-spy="affix" data-offset-top="400">
.affix {
/* fixed navbar style */
}
.affix-top {
/* navbar style at top */
background:transparent;
border-color:transparent;
}
将data-offset-top
属性设置为您希望导航栏转换的像素高度。
答案 2 :(得分:0)
const body = document.body;
const header = document.querySelector("header");
const scrollUp = "scroll-up";
const scrollDown = "scroll-down";
let lastScroll = 0;
window.addEventListener("scroll", () => {
const currentScroll = window.pageYOffset;
if (currentScroll == 0) {
header.classList.remove(scrollUp);
return;
}
if (currentScroll > lastScroll && !body.classList.contains(scrollDown)) {
// down
header.classList.remove(scrollUp);
header.classList.add(scrollDown);
} else if (
currentScroll < lastScroll &&
header.classList.contains(scrollDown)
) {
// up
header.classList.remove(scrollDown);
header.classList.add(scrollUp);
}
lastScroll = currentScroll;
});