如果scrollTop == 0,如何删除一个类?

问题描述 投票:0回答:1

如果scrollTop == 0,如何删除一个类?

现在,当您向下滚动页面时,导航栏将按预期工作。

但是当我将页面滚动到顶部时 - 该类不会被删除。告诉我在这种情况下该怎么做。

我的代码

var navbar = document.querySelector('.navbar');
var scrollTop = window.pageYOffset;
var body = document.querySelector('body');

window.onscroll = function() {
  if (window.pageYOffset > scrollTop) {
    navbar.classList.add('slideUp');

    body.classList.remove('styling');
    navbar.classList.remove('styling');
  } else if (window.pageYOffset < scrollTop) {
    body.classList.add('styling');
    navbar.classList.add('styling');
    navbar.classList.remove('slideUp');
  }

  scrollTop = window.pageYOffset;

}
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  padding-top: 80px;
  min-height: 2000px;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: #00f;
  height: 80px;
  transition: transform .5s ease;
}

.navbar.styling {
  height: 60px;
}

.navbar.slideUp {
  transform: translateY(-100%);
}
<nav class="navbar"></nav>

谢谢。我很乐意提供任何帮助

javascript html5 css3
1个回答
1
投票

scrollTop更新其值后,请检查window.pageYOffset

var navbar = document.querySelector('.navbar');
var scrollTop = window.pageYOffset;
var body = document.querySelector('body');

window.onscroll = function() {
  if (window.pageYOffset > scrollTop) {
    navbar.classList.add('slideUp');

    body.classList.remove('styling');
    navbar.classList.remove('styling');
  } else if (window.pageYOffset < scrollTop) {
    body.classList.add('styling');
    navbar.classList.add('styling');
    navbar.classList.remove('slideUp');
  }

  scrollTop = window.pageYOffset;

  // Here
  if (scrollTop === 0) {
    body.classList.remove('styling');
    navbar.classList.remove('styling');
  }
  
  console.log(`for scrollTop = ${scrollTop}, classes are:`, navbar.classList.value);
}
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  padding-top: 80px;
  min-height: 2000px;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: #00f;
  height: 80px;
  transition: transform .5s ease;
}

.navbar.styling {
  height: 60px;
}

.navbar.slideUp {
  transform: translateY(-100%);
}
<nav class="navbar"></nav>
© www.soinside.com 2019 - 2024. All rights reserved.