DIV의 스크롤 오디오
Sep 22 2020
페이지의 선택한 영역에서 오디오를 활성화하고 싶습니다. 사용자가이 요소를 스크롤하면 오디오가 중지됩니다. 이 솔루션을 찾았지만 문제는 창, 모니터, 브라우저 종류 등의 해상도에 따라 픽셀 값이 다르다는 것입니다.
var playing = false;
var audioElm = $('#soundTour').get(0); $(window).scroll(function() {
var pageScroll = $(window).scrollTop();
if(!playing && pageScroll > 500 && pageScroll < 3000){
audioElm.play();
playing = true;
}else if(pageScroll > 3000 || pageScroll < 500){
audioElm.pause();
playing = false;
}
});
이를 위해 DIV에서 해결책 을 찾고 싶습니다 . 내 한 페이지는 다음과 같습니다.https://alvarotrigo.com/fullPage/examples/navigationV.html#firstPage 예를 들어 배경 사운드가 첫 번째와 두 번째 페이지에서 자동 재생되고 사용자가 세 번째 페이지에 참여하면 중지되기를 원합니다.
도움이 필요하세요?
답변
AlexanderSmirnov Sep 22 2020 at 14:18
아래 코드에서 세 번째 블록의 30 %가 표시되면 사운드가 재생되기 시작합니다.
<html>
<head>
<meta charset="utf-8" />
<style>
body { margin: 0; padding: 0; }
</style>
</head>
<body>
<audio src="/sound.wav"></audio>
<div style="height: 100%; background: #ff5555">first page</div>
<div style="height: 100%; background: #55ff55">second page</div>
<div id="d3" style="height: 100%; background: #5555ff">third page</div>
<script>
const el = document.querySelector("audio");
let playing = false;
window.addEventListener('scroll', (e) => {
const scroll = e.target.body.scrollTop;
const rect = document.getElementById("d3").getBoundingClientRect();
const top = rect.top;
if (!playing && top > rect.height / 3) {
el.play();
playing = true;
} else if (top < rect.height / 3) {
el.pause();
playing = false;
}
});
</script>
</body>
</html>
댓글 후 업데이트 :
<html>
<head>
<meta charset="utf-8" />
<style>
body { margin: 0; padding: 0; }
</style>
</head>
<body>
<div id="d1" style="height: 100%; background: #ff5555">first page</div>
<div id="d2" style="height: 100%; background: #55ff55">second page</div>
<div id="d3" style="height: 100%; background: #5555ff">third page</div>
<script>
const soundfiles = ["sound.wav", "sound2.wav", "sound.wav"];
const divIds = ["d1", "d2", "d3"];
const els = soundfiles.map((filename, index) => {
const el = document.createElement("audio");
el.src = "/" + filename;
document.body.appendChild(el);
return el;
})
const playing = new Array(divIds.length).fill(false);
window.addEventListener('scroll', (e) => {
const scroll = e.target.body.scrollTop;
const rects = divIds.map(id => document.getElementById(id).getBoundingClientRect());
const tops = rects.map(rect => rect.top);
tops.forEach((top, ind) => {
if (!playing[ind] && top <= rects[ind].height * 2 / 3 && top > - rects[ind].height * 1 / 3) {
els[ind].play();
playing[ind] = true;
} else if (playing[ind] && (top > rects[ind].height * 2 / 3 || top < -rects[ind].height * 1 / 3)) {
els[ind].pause();
playing[ind] = false;
}
});
});
</script>
</body>
</html>