javascript - 在添加和删除两个类之间添加动画

标签 javascript jquery css css-transitions

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

  -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>

执行此操作的最佳方法是什么(平稳地上下移动)?

最佳答案

条纹上下跳跃是因为你没有在.fixed-top中设置bottom的值,在.fixed-bottom中设置top的值,那么transition prosessor不能没有意识到过渡的属性。您需要让 window.height() 正确传输。您可以使用 jquery 来完成,这会使您的 css 更短 看片段

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>

关于javascript - 在添加和删除两个类之间添加动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40772593/

相关文章:

javascript - 通过 JavaScript 创建 HTML 页面

javascript - 联系表 7 - 日期选择器

javascript - 单击 div 时滚动到顶部,如果滚动在顶部则滚动到底部

javascript - 输入类型 radio 在 iPhone 上不工作

javascript - Jquery UI 位置 : wrong top offset

javascript - 无法读取未定义的属性 game.state.add()

javascript - 如何使用dojo工具包在本地保存json文件

javascript - 如何限制div的旋转 Angular

javascript - css真的不理我

css - 是否可以仅使用 CSS 创建一个向下的按钮(包括图像)?