在javascript中滚动时为什么我的文本没有移动?

时间:2019-10-14 14:28:13

标签: javascript

我正在尝试在滚动条上创建视差效果。 “ Po Ta To”必须以不同的速度滚动。但是它不起作用。

window.addEventListener("scroll", function(e) {

  const target = document.querySelectorAll('.parallax');
  var index = 0,
    length = target.length;

  for (index; index < length; index++) {
    var pos = window.pageYOffset * target[index].dataset.speed;
    target[index].style.transform = 'translate3d(0px, ' + pos + 'px, 0px)';
  }
});
* {
  margin: 0px;
  padding: 0px;
  width: 100%;
  font-family: Montserrat;
  height: 200vh;
}

section {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

ul {
  height: 30vh;
  text-align: center;
  white-space: nowrap;
}

li {
  font-size: 100px;
  font-weight: bold;
  text-align: center;
  display: inline;
}
<section>
  <ul>
    <li class="parallax" data-speed="2">PO</li>
    <li class="parallax" data-speed="1.5">TA</li>
    <li class="parallax" data-speed="2.3">TO</li>
  </ul>
</section>

1 个答案:

答案 0 :(得分:1)

transform在您的li元素上无法正常工作,因为它们是inline。他们必须是block才能正常工作。

在此处参阅inline-block。我显然不得不为它们设置一个宽度,以阻止它们占据页面的整个宽度:

window.addEventListener("scroll", function(e) {
  const target = document.querySelectorAll('.parallax');
  var index = 0,
    length = target.length;

  for (index; index < length; index++) {
    var pos = window.pageYOffset * target[index].dataset.speed;
    target[index].style.transform = 'translateY(' + pos + 'px)';
  }
});
* {
  margin: 0px;
  padding: 0px;
  width: 100%;
  font-family: Montserrat;
  height: 200vh;
}

section {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

ul {
  height: 30vh;
  text-align: center;
  white-space: nowrap;
}

li {
  font-size: 100px;
  font-weight: bold;
  text-align: center;
  display: inline-block;
  width: 130px;
}
<section>
  <ul>
    <li class="parallax" data-speed="2">PO</li>
    <li class="parallax" data-speed="1.5">TA</li>
    <li class="parallax" data-speed="2.3">TO</li>
  </ul>
</section>

进行必要的调整以达到所需的效果。