如何使元素平滑地向上滑动页面?

时间:2019-05-22 22:08:30

标签: javascript css css-transitions

我有以下代码,其中包含定位的隐藏div(.converter),并且我使用JS根据用户的滚动使其上下滑动。但是我想使其顺利进行,我认为过渡可以胜任。

window.addEventListener('scroll', function() {

  var scroll = window.pageYOffset || document.documentElement.scrollTop;

  var element = document.querySelector(".converter");

  if (scroll >= 400) {
    element.classList.add("atcbottomactive");
  } else {
    element.classList.remove("atcbottomactive");
  }

});
.converter {
	position: fixed; 
	height: 60px; 
	width: 100%; 
	bottom: -200; 
	background: red; 
	transition: 1s;
	z-index: 10000;
}

.ccontent {
	display: inline-flex;
	width: 100%;
	padding: 10px 5%;
}

.atcbottomactive{
	bottom:0;
	transition: 1s;
}

.page {
  background: green;
  height: 1500px;
  width: 100%;
 }
<div class="page">Scroll me: 400px</div>
<div class="converter">
  <div class="ccontent"></div>
</div>

预先感谢

1 个答案:

答案 0 :(得分:3)

太近了!您所缺少的只是.converter类bottom属性上的'px'。由于-200不是有效的底部,因此您正从未设置的底部变为0px,该像素不能设置动画/过渡。

window.addEventListener('scroll', function() {

  var scroll = window.pageYOffset || document.documentElement.scrollTop;

  var element = document.querySelector(".converter");

  if (scroll >= 400) {
    element.classList.add("atcbottomactive");
  } else {
    element.classList.remove("atcbottomactive");
  }

});
.converter {
	position: fixed; 
	height: 60px; 
	width: 100%; 
	bottom: -200px; 
	background: red; 
	transition: 1s;
	z-index: 10000;
}

.ccontent {
	display: inline-flex;
	width: 100%;
	padding: 10px 5%;
}

.atcbottomactive{
	bottom:0;
	transition: 1s;
}

.page {
  background: green;
  height: 1500px;
  width: 100%;
 }
<div class="page">Scroll me: 400px</div>
<div class="converter">
  <div class="ccontent"></div>
</div>