【问题标题】:Adding animation between adding and removing two classes在添加和删除两个类之间添加动画
【发布时间】:2017-04-07 22:37:12
【问题描述】:

我正在制作下面的演示。为什么我无法在添加和删除两个类fixed-topfixed-bottom 之间生成平滑过渡(类似于平滑滚动),而我已经在其中添加了以下 css 角色?

  -webkit-transition: all 3s ease;
  -moz-transition: all 3s ease;
  -o-transition: all 3s ease;
  transition: all 3s ease;

var lastScrollTop = 0;
$(window).scroll(function(event) {
  var st = $(this).scrollTop();
  if (st > lastScrollTop) {
    if (st > 500) {
      $('.box').removeClass("fixed-bottom").addClass("fixed-top");
    }
  } else {
    if (st < 500) {
      $('.box').removeClass("fixed-top").addClass("fixed-bottom");
    }
  }
  lastScrollTop = st;
});
html,
body {
  height: 100%;
}

.container {
  height: 2000px;
}

.box {
  width: 100%;
  height: 50px;
  background: #777;
}

.fixed-top {
  position: fixed;
  top: 0;
  -webkit-transition: all 3s ease;
  -moz-transition: all 3s ease;
  -o-transition: all 3s ease;
  transition: all 3s ease;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  -webkit-transition: all 3s ease;
  -moz-transition: all 3s ease;
  -o-transition: all 3s ease;
  transition: all 3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box fixed-bottom"></div>
</div>

最好的方法是什么(平滑上下移动)?

【问题讨论】:

    标签: javascript jquery css css-transitions


    【解决方案1】:

    条带上下跳动是因为你没有在.fixed-top 中设置bottom 的值,在.fixed-bottom 中设置top 的值,那么transition prosessor 就无法实现要transition 的那个属性。您需要让 window.height() 正确过渡。您可以使用 jquery 来完成,这使您的 css 更短 看sn-p

    var lastScrollTop = 0;
    var y = $( window ).height() - $('.box').height() + "px";
    $('.box').css("top", y);
    $(window).scroll(function(event) {
      var st = $(this).scrollTop();
      if (st > lastScrollTop) {
        if (st > 500) {
          $('.box').css("bottom", y);
          $('.box').css("top","0");
        }
      } else {
        if (st < 500) {
          $('.box').css("top", y);
          $('.box').css("bottom","0");
        }
      }
      lastScrollTop = st;
    });
    html,
    body {
      height: 100%;
    }
    
    .container {
      height: 2000px;
    }
    
    .box {
      width: 100%;
      height: 50px;
      position: fixed;
      bottom: 0;
      background: #777;
      -webkit-transition: all 3s ease;
      -moz-transition: all 3s ease;
      -o-transition: all 3s ease;
      transition: all 3s ease;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
      <div class="box fixed-bottom"></div>
    </div>

    【讨论】:

    • 非常感谢 Banzay
    猜你喜欢
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2015-06-28
    相关资源
    最近更新 更多