在If语句中停止转换

时间:2018-12-11 19:35:39

标签: jquery transition

以下代码旨在在向下滚动时隐藏导航栏,以及根据窗口的位置在背景色之间进行切换。从最高位置向下滚动时,背景变成白色,但只有在第一次转换完成后(scrollUp)。

我遇到的问题是,当滚动回到顶部时,TrasitionEnd函数在到达顶部之后完成,导致背景再次变白。

如果满足第一个条件(currentScrollTop == 0),如何在最后一个If语句中“破坏” TransitionEnd函数?

$(document).ready(function() {
  'use strict';

  var c, currentScrollTop = 0,
    navbar = $('nav');

  $(window).scroll(function() {
    var a = $(window).scrollTop();
    var b = navbar.height();

    currentScrollTop = a;

    if (c < currentScrollTop) {
      navbar.addClass("scrollUp");
    } else if (c > currentScrollTop) {
      navbar.removeClass("scrollUp");
    }
    if (currentScrollTop == 0) {
      navbar.css("background", "none")
    } else if ($(window).scrollTop() > 0) {
      navbar.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
        function(e) {
          navbar.css("background", "#fff");
        });
    }
    c = currentScrollTop;
  });
});
body {
  background-image: url(http://kanto-audio.local/wp-content/uploads/2018/12/header1.jpg);
  min-height: 3000px;
  padding: 0;
  margin: 0;
  font-family: "Open Sans", sans-serif;
}

.container {
  width: 80%;
  margin: 0 auto;
  clear: both;
}

a {
  display: inline-block;
  color: #333;
  text-decoration: none;
}

.whiteOut {
  background: #fff;
}

nav {
  background: #fff0;
  height: 80px;
  line-height: 80px;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9998;
  transition: all 0.5s;
}

nav.scrollUp {
  transform: translateY(-80px);
}

nav ul.navbar-menu {
  margin: 0;
  padding: 0;
  display: inline-block;
  float: right;
}

nav ul.navbar-menu li {
  display: inline-block;
  margin: 0 10px;
}

nav ul.navbar-menu li a {
  color: #666;
  font-size: 14px;
}

nav a#brand {
  text-transform: uppercase;
  foat: left;
  font-weight: 800;
  font-size: 20px;
}

nav button {
  background: none;
  width: 30px;
  height: 40px;
  margin-top: 20px;
  border: none;
  float: right;
  display: inline-block;
  cursor: pointer;
  display: none;
}

nav button span {
  width: 30px;
  height: 40px;
  height: 2px;
  background: #333;
  display: block;
  margin: 5px 0;
}

@media (max-width: 768px) {
  nav ul.navbar-menu {
    display: none;
  }
  nav button {
    display: block;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div class="container">
    <a href="#" id="brand">Brand</a>
    <button>
      <span></span>
      <span></span>
      <span></span>
    </button>

    <ul class="navbar-menu">
      <li><a href="#">Home</a></li>
      <li><a href="#">page c</a></li>
      <li><a href="#">page b</a></li>
      <li><a href="#">page c</a></li>
      <li><a href="#">page s</a></li>
    </ul>

  </div>
</nav>

0 个答案:

没有答案