Javascript 更改滚动页面上的类名
我想进行一个java脚本调用,以更改导航的类名 第一次加载页面时,我的导航是这样的:Javascript 更改滚动页面上的类名,javascript,Javascript,我想进行一个java脚本调用,以更改导航的类名 第一次加载页面时,我的导航是这样的: <nav class="navbar navbar-inverse" role="navigation" id="topNav"> 我希望这个事件在页面滚动到最顶端时立即发生。如果页面被卷回顶部,我希望它回到原来的状态。当前,当我滚动时,什么也没有发生。您可以使用 var scrollPosition = $(window).scrollTop(); 如果scrollPosition为0,则表示
<nav class="navbar navbar-inverse" role="navigation" id="topNav">
我希望这个事件在页面滚动到最顶端时立即发生。如果页面被卷回顶部,我希望它回到原来的状态。当前,当我滚动时,什么也没有发生。您可以使用
var scrollPosition = $(window).scrollTop();
如果scrollPosition
为0
,则表示您处于最顶端。如果大于0
,则表示用户已向下滚动
$(window).scroll(function() {
if ($(window).scrollTop() === 0) {
// We are at the top of the page and want to remove the class
$('#topNav').removeClass('navbar-fixed-top');
} else {
$('#topNav').addClass('navbar-fixed-top');
}
});
当用户滚动到导航栏顶部时,此代码会立即从导航栏中删除类navbar fixed top
,并在用户滚动离开顶部时将该类添加到导航栏中
假设您的CSS看起来像这样:
.navbar-fixed-top {
position: fixed;
top: 0;
}
当您仅为scrollPosition>200左右的值添加类navbar fixed top
时,可以创建酷炫效果
看这把小提琴:
$(window).scroll(function() {
if ($(window).scrollTop() === 0) {
// We are at the top of the page and want to remove the class
$('#topNav').removeClass('navbar-fixed-top');
} else {
$('#topNav').addClass('navbar-fixed-top');
}
});
.navbar-fixed-top {
position: fixed;
top: 0;
}