javascript - 使用 JS 的水平视差滚动

标签 javascript html css

我正在尝试获得水平视差效果。我在父 div 中有两个子 div。我想在以不同速度滚动的同时向相反方向移动两个 div。但是它不起作用。我怀疑使用 top 和 left 属性可能是错误的原因。但是我确实需要 top 和 left 属性来将 div 放置在准确的位置。

我的 HTML:

<div id='frst' style= 'height:600px;'>
</div>
<div class= 'div1' style= " position:relative;width: 100%; height: 500px; background-color: red; top: 20%;">
    <div id= 'image'>
    </div> 
    <div id= 'image2'>
    </div>
</div>

没有我的 CSS:

#image{ background:green ; width:100px; height: 100px; top:20px; position: absolute;}
#frst{color:white; }
#image2{ background: yellow;  width:100px;height: 100px; left: 60%;top:29px;position: absolute;}

我正在使用 JS 在滚动条上向左或向右移动 div #image 和 #image2:

function parallax() {
   var image= document.getElementById('image');
   var image2= document.getElementById('image2');

   image.style.margin-right= -(window.pageYOffset/ 10) + 'px';
   image2.style.margin-left= -(window.pageYOffset/ 9) + 'px';

}

window.addEventListener("scroll",parallax,false)

最佳答案

这就是您所期待的吗? https://jsfiddle.net/0or5cgz4/7/

将 right 添加到 #image 和 #first 作为相对位置并设置宽度/高度

#image{ background:green ; width:100px; height: 100px; top:0px;right:0; position: absolute;}
#frst{color:white;position:relative; width:100px;height:100px;}

关于javascript - 使用 JS 的水平视差滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935036/

相关文章:

javascript - 如何使用 *ngFor 和 *ngIf Angular 4 将数据传递到不同的模板

Javascript 窗口对象

html - img 上不透明度的 CSS 关键帧动画不起作用

html - 为什么关闭 1 像素边框会在固定位置标题和 Flex 增长的情况下产生 75 像素溢出?

javascript - 使用 jQuery 构建可自定义的起始页

javascript - 如何更新 d3 线图上的标签?

javascript - 如何显示 cookie 的输出?

javascript - 同步 Canvas 绘图/阅读

javascript - 尝试使用链接延迟,但我尝试的任何代码都不起作用

html - div有问题吗?