在这段代码中,我想用一些元素产生视差效果,但无论我做什么,只有一个元素在移动,我不知道问题出在哪里:/
我尝试了不同的东西,但无论制作了多少对象,只有最后一个表格数组(ParaElements)在移动。
function ParaElement(x, y, z, id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
document.getElementById("paralax").innerHTML +=
'<div class="para-elmt"> </div>';
this.htmlObj = document.getElementsByClassName("para-elmt")[id];
this.positionChange = function (tx, ty) {
this.htmlObj.style.top = String(tx) + "px";
this.htmlObj.style.left = String(ty) + "px";
this.htmlObj.style.zIndex = this.z;
};
this.positionChange(this.x, this.y);
this.scrollHandler = function () {
let scrollPosition = document.documentElement.scrollTop;
let tx = this.x - scrollPosition / this.z;
let ty = this.y;
this.positionChange(tx, ty);
};
}
var ParaElements = [];
ParaElements.push(new ParaElement("30", "100", "25", "0"));
ParaElements.push(new ParaElement("100", "300", "50", "1"));
ParaElements.push(new ParaElement("200", "200", "10", "2"));
$(document).on("scroll", function () {
for (let i = 0; i < ParaElements.length; i++) {
ParaElements[i].scrollHandler();
}
});
body {
min-height: 2000px;
}
#paralax {
width: 100%;
height: 100%;
position: fixed;
margin: 0;
}
#paralax .para-elmt {
position: absolute;
width: 100px;
height: 100px;
border-radius: 50px;
background-color: teal;
z-index: 9999;
}
<html>
<body>
<div id="paralax">
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
</body>
慕斯709654
相关分类