为什么window.onscroll函数的行为很奇怪?

时间:2018-12-18 04:19:03

标签: javascript html css

我对编码和一切都很陌生,但是已经对教程和所有这些东西有了很好的了解。

当有人向下滚动时,我正在尝试更改此徽标。它正在工作,但是我想弄清楚为什么当页面首次加载并且有人向下滚动时,它会在一开始就快速切换类。它只是在一开始就做,但是之后就可以了。

有任何提示或建议吗??谢谢!!

window.onscroll = function() {
  navScroll()
};

function navScroll() {
  var logoNav = document.getElementById("bgNav");

  if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
    logoNav.className = "play";
  } else {
    logoNav.className = "playBack";
  }
}
@charset "UTF-8";

.container {
  height: 2000px;
  background-color: #c3c3c3;
}

@keyframes play60 {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: -30000px 0px;
  }
}

@keyframes play60Back {
  0% {
    background-position: -30000px 0px;
  }
  100% {
    background-position: 0 0;
  }
}

#bgNav.play {
  animation-name: play60;
  animation-fill-mode: forwards;
}

#bgNav.playBack {
  animation-name: play60Back;
  animation-fill-mode: forwards;
}

#bgNav {
  height: 117px;
  width: 500px;
  position: fixed;
  animation-duration: 2000ms;
  animation-timing-function: steps(60);
  background-repeat: no-repeat;
  background-image: url("https://metro1.000webhostapp.com/metro-nav-animated.svg");
}
<!DOCTYPE html>
  <html>
  <body>
  <div class="container">
    <div class="" id="bgNav"></div>

  </div>
  </body>
  </html>

1 个答案:

答案 0 :(得分:4)

这很好

} else if(logoNav.className === "play") {
    logoNav.className = "playBack";
}

window.onscroll = function() {
  navScroll()
};

function navScroll() {
  var logoNav = document.getElementById("bgNav");

  if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
    logoNav.className = "play";
  } else if(logoNav.className === "play") {
    logoNav.className = "playBack";
  }
}
@charset "UTF-8";

.container {
  height: 2000px;
  background-color: #c3c3c3;
}

@keyframes play60 {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: -30000px 0px;
  }
}

@keyframes play60Back {
  0% {
    background-position: -30000px 0px;
  }
  100% {
    background-position: 0 0;
  }
}

#bgNav.play {
  animation-name: play60;
  animation-fill-mode: forwards;
}

#bgNav.playBack {
  animation-name: play60Back;
  animation-fill-mode: forwards;
}

#bgNav {
  height: 117px;
  width: 500px;
  position: fixed;
  animation-duration: 2000ms;
  animation-timing-function: steps(60);
  background-repeat: no-repeat;
  background-image: url("https://metro1.000webhostapp.com/metro-nav-animated.svg");
}
<!DOCTYPE html>
  <html>
  <body>
  <div class="container">
    <div class="" id="bgNav"></div>

  </div>
  </body>
  </html>