Last active
September 27, 2023 10:00
-
-
Save megurock/6007a7c13fa49d985e5983d508266713 to your computer and use it in GitHub Desktop.
IntersectionObserver を使ったパララックス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Document</title> | |
<style> | |
body { | |
margin: 0; | |
} | |
.foo { | |
background-color: yellow; | |
height: calc(100vh + 100px); | |
} | |
.bar { | |
background-color: orange; | |
height: 2000px; | |
} | |
.parallax { | |
position: relative; | |
} | |
/* これは IntersectionObserver の監視ターゲットとして機能します。 */ | |
.parallax__detector { | |
position: absolute; | |
top: 0; | |
left: 0; | |
width: 100px; | |
height: 50vh; | |
background-color: rgba(255, 0, 0, 0.5); | |
pointer-events: none; | |
} | |
.parallax__image { | |
aspect-ratio: 16/4; | |
object-fit: cover; | |
width: 100%; | |
height: auto; | |
display: block; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="foo"></div> | |
<div class="parallax"> | |
<div class="parallax__detector"></div> | |
<img | |
class="parallax__image" | |
src="https://via.placeholder.com/1600x1200" | |
/> | |
</div> | |
<div class="bar"></div> | |
</body> | |
<script> | |
const onInterSect = ([entry], observer) => { | |
console.log("ratio", entry.intersectionRatio); | |
}; | |
const init = () => { | |
const observerOptions = { | |
rootMargin: "0px 0px -100px 0px", | |
threshold: Array.from({ length: 101 }, (_, i) => i * 0.01), // 0 から 1 を要素とする配列 | |
}; | |
const observer = new IntersectionObserver(onInterSect, observerOptions); | |
observer.observe(document.querySelector(".parallax__detector")); | |
}; | |
init(); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment