背景をYouTubeにしスクロールで動画を切り替える
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>セクションごとに切り替わる背景動画</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
section {
position: relative;
width: 100%;
min-height: 100vh;
padding: 4rem 1rem;
display: flex;
align-items: center;
justify-content: center;
}
.section-white {
background: #fff;
color: #000;
}
.content {
position: relative;
z-index: 1;
color: white;
max-width: 800px;
text-align: center;
}
.video-container {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: -2;
pointer-events: none;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
.video-container iframe {
width: 56.25vh; /* 9:16 比率 */
width: 100%; /* 9:16 比率 */
height: 100vh;
object-fit: cover;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: -1;
}
</style>
</head>
<body>
<!-- 背景動画&オーバーレイ -->
<div class="video-container">
<iframe
id="bg-video"
src="https://www.youtube.com/embed/_tZsIajVXNg?autoplay=1&mute=1&loop=1&playlist=_tZsIajVXNg&controls=0&modestbranding=1&showinfo=0"
frameborder="0"
allow="autoplay; encrypted-media"
allowfullscreen
></iframe>
</div>
<div class="overlay"></div>
<!-- セクションたち -->
<section class="section-white">
<div class="content">
<h1>1つ目のセクション(白背景)</h1>
<p>ここは背景なしです。</p>
</div>
</section>
<section data-video="_tZsIajVXNg">
<div class="content">
<h1>2つ目のセクション(動画1)</h1>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
<p>背景動画1が再生されます。</p><br><br><br>
</div>
</section>
<section data-video="k9JDXcIfVTg">
<div class="content">
<h1>3つ目のセクション(動画2)</h1>
<p>ここでは動画2に切り替わります。</p><br>
<p>ここでは動画2に切り替わります。</p><br>
<p>ここでは動画2に切り替わります。</p><br>
<p>ここでは動画2に切り替わります。</p><br>
<p>ここでは動画2に切り替わります。</p><br>
</div>
</section>
<section data-video="dZc-ekD3540">
<div class="content">
<h1>4つ目のセクション(動画3)</h1>
<p>ここではさらに別の動画になります。</p>
</div>
</section>
<script>
const videoIframe = document.getElementById("bg-video");
const sections = document.querySelectorAll("section[data-video]");
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const videoId = entry.target.getAttribute("data-video");
const newSrc = `https://www.youtube.com/embed/${videoId}?autoplay=1&mute=1&loop=1&playlist=${videoId}&controls=0&modestbranding=1&showinfo=0`;
if (!videoIframe.src.includes(videoId)) {
videoIframe.src = newSrc;
}
}
});
}, {
threshold: 0.6
});
sections.forEach(section => {
observer.observe(section);
});
</script>
</body>
</html>
コメント