ちょっとパララックス動作を実装したい時のメモ。
シンプルにスクロール量に応じてtransformのY値を変更。
読み込んだ時にも初期値を設定。
/*
* windows on scroll
*/
function getYPosition() {
var top = window.pageYOffset || document.documentElement.scrollTop;
return top;
}
function movePallax() {
const pal_elements = document.getElementsByClassName("pal_element");
//if pal_elements exists
if (pal_elements.length > 0) {
//speed
const speed = 0.1;
//set value
function set() {
Array.prototype.forEach.call(pal_elements, function (e) {
const direction = e.getAttribute("data-direction");
if (direction == "up") {
const move = getYPosition() * -1 * speed;
e.style.transform = "translateY(" + move + "px)";
}
if (direction == "down") {
const move = getYPosition() * speed;
e.style.transform = "translateY(" + move + "px)";
}
});
}
//set initial value
set();
//when window is scrolled set them again
window.addEventListener("scroll", function () {
set();
});
} else {
return false;
}
return false;
}
let movePallax_value = movePallax();