1 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
通過(guò)在每次啟動(dòng) ParaElement 時(shí)使用 innerHTML,您將破壞以前用來(lái)抓取元素的選擇器。這就是為什么只有最后一個(gè)在移動(dòng)。這樣的事情應(yīng)該可以解決問(wèn)題。
function ParaElement(x, y, z, id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
this.htmlObj = document.getElementsByClassName("para-elmt")[this.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);
};
}
// Let's define the number of element we want, by creating an array with the differents parameters.
// I removed the last parameter from the arrays because it can be added directly when we will loop over the arrays.
let paraElementsParams = [["30", "100", "25"], ["100", "300", "50"], ["200", "200", "10"]]
var ParaElements = [];
// Instead of initializing by hand, let's loop over the elements in our parameters array so we can first create all the dom elements
for (let i = 0; i < paraElementsParams.length; i++) {
document.getElementById("paralax").innerHTML += '<div class="para-elmt"> </div>';
}
// Then, let's loop again so we can initialize our elements without losing the node references.
for (let i = 0; i < paraElementsParams.length; i++) {
// we add i at the end of the initialization using the current loop index
ParaElements.push(new ParaElement(...paraElementsParams[i], i));
}
$(document).on("scroll", function () {
for (let i = 0; i < ParaElements.length; i++) {
ParaElements[i].scrollHandler();
}
});
添加回答
舉報(bào)