使用body标签实现视差时,window.onscroll不再有效

时间:2022-05-29 20:26:27

I am having trouble getting the onscroll event when I try to implement a parallax effect using the body tag. See my code below.

当我尝试使用body标签实现视差效果时,我无法获得onscroll事件。请参阅下面的代码。

When I comment out the sections in the CSS corresponding to html, parallax, parallax-front and parallax-back (i.e. all the CSS that makes the parallax work), the onscroll event works fine. As soon as I uncomment them, it stops working. I have also tried document.onscroll, document.body.onscroll and these do not work either.

当我在CSS中注释掉对应于html,parallax,parallax-front和parallax-back的部分(即所有使视差工作的CSS)时,onscroll事件工作正常。一旦我取消注释它,它就会停止工作。我也尝试过document.onscroll,document.body.onscroll,这些也不起作用。

Why is it not working and how can I get the onscroll event to work?

为什么它不起作用,我怎样才能让onscroll事件发挥作用?

function log(msg) {
  console.log(new Date() + ": " + msg);
}

window.onload = function() {
  log("loaded");
};

window.onscroll = function() {
  log(document.body.scrollTop);
};
html {
  overflow: hidden;
}

.parallax {
  margin: 0 0;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  perspective: 1px;
  perspective-origin: 0 0;

  overflow-x: hidden;
  overflow-y: auto;
}

.parallax-front {
  transform: translateZ(0px);
}

.parallax-back {
  transform-origin: 0 0;
  transform: translateZ(-2px) scale(3);
}

#banner {
  height: 10rem;
  line-height: 10rem;
  background: pink;
  border: 8px solid red;
  text-align: center;
}

#content {
  height: 50rem;
  background: rgba(224, 224, 255, 0.9);
  border: 8px solid blue;
  text-align: center;
}
  <body class="parallax">
    <div class="parallax-back">
      <div id="banner">Banner</div>
    </div>
    <div class="parallax-front">
      <div id="content">Content</div>
    </div>
  </body>

1 个解决方案

#1


0  

Well you shouldn't be able to scroll anywhere when you have overflow: hidden applied to html.

好吧,当你有溢出时你不应该在任何地方滚动:隐藏应用于HTML。

#1


0  

Well you shouldn't be able to scroll anywhere when you have overflow: hidden applied to html.

好吧,当你有溢出时你不应该在任何地方滚动:隐藏应用于HTML。