滚动页面时如何使对象向下移动?

时间:2019-07-31 10:05:36

标签: javascript parallax

我发现了一个运行良好的paralax脚本,但是红色对象是否有可能仅取决于黄色窗口的高度,而不取决于绿色窗口,并且它始终离顶部20px?

如果绿色大小发生变化,例如300vh,则在移动页面之后,页面已经较低。我找到了其他脚本,但是每个人都有这个问题。

可能是红色下移的另一种解决方案?

window.requestAnimationFrame = window.requestAnimationFrame
 || window.mozRequestAnimationFrame
 || window.webkitRequestAnimationFrame
 || window.msRequestAnimationFrame
 || function(f){setTimeout(f, 1000/60)}
 

var red = document.getElementById('red')


 
function parallaxTop(){
 var scrolltop = window.pageYOffset 
 red.style.top = -scrolltop * -.3 + 'px'
}
 
window.addEventListener('scroll', function(){ 
 requestAnimationFrame(parallaxTop) 
}, false)
.green {
  background: green;
  position: relative;
  height: 100vh;
  width: 100%;
}
.yellow {
  background: yellow;
  position: relative;
  height: 100vh;
  width: 100%;
}
#red {
  background: red;
  position: absolute;
  top: 20px;
  left: 20px;
  height: 100px;
  width: 100px;
}
.black {
  background: black;
  position: relative;
  bottom: 20px;
  right: 20px;
  height: 100px;
  width: 100px;
}
.orange {
  background: orange;
  position: relative;
  height: 100vh;
  width: 100%;
}
<div class="green"></div>
<div class="yellow">
  <div id="red"></div>
</div>
<div class="orange"></div>
    

0 个答案:

没有答案