我想在section#employee-dance
启用音频。
如果用户滚动此元素,音频将暂停。
目前,我只在用户滚动到顶部时应用代码,音频将暂停。 向下滚动到下一个元素,音频仍在播放。
您可以在此处查看我的代码和示例:
// Scrool div anchor
var targetOffset = $("#employee").offset().top;
$('#employee-dance').hide();
var myAudio = document.getElementById("myAudio");
var $w = $(window).scroll(function(){
if ( $w.scrollTop() >= targetOffset) {
setTimeout(
function(){
$('#employee').replaceWith($('#employee-dance'));
$('#employee-dance').fadeIn(2000);
if($('#employee-dance').is(':visible')){
myAudio.play();
myAudio.volume = 0.2;
$(".music-node").css('display','block');
}
},
500
);
}
else{
myAudio.pause();
$(".music-node").css('display','none');
myAudio.volume = 0;
}
});

#top-text, #employee-dance, #down-text, #employee {
height: 300px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="top-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta dolor aspernatur reiciendis voluptates enim natus distinctio aliquid. Aut quaerat adipisci nam numquam alias suscipit, consectetur eveniet eius culpa quia explicabo!</section>
<hr>
<section id="employee">
</section>
<section id="employee-dance">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi pariatur nulla delectus dolores. Dolores veniam rerum consequuntur, odit repellendus. Suscipit hic tempore magni ducimus cupiditate adipisci, repellat illum laboriosam eius?
<div class="raido-employee">
<audio loop id="myAudio">
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mpeg">
</audio>
</div>
<div class="music-node"></div>
</section>
<hr>
<section id="down-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa error, aspernatur eius labore recusandae beatae, sapiente, ad id impedit facilis qui debitis similique maxime perspiciatis atque quas dolore, nihil harum.</section>
&#13;
答案 0 :(得分:1)
// Scrool div anchor
var danceEl = $("#employee-dance");
var danceElOffset = danceEl.offset().top;
var danceElHeight = danceEl.height();
var myAudio = document.getElementById("myAudio");
var $w = $(window).scroll(function() {
if ($w.scrollTop() >= danceElOffset && $w.scrollTop() <= (danceElOffset + danceElHeight)) {
myAudio.play();
myAudio.volume = 0.2;
} else {
myAudio.pause();
myAudio.volume = 0;
}
});
#employee,
#employee-dance,
#down-text {
height: 700px;
}
#employee {
background: green;
}
#employee-dance {
background: red;
}
#down-text {
background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="employee"></section>
<section id="employee-dance">
<audio loop id="myAudio">
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mpeg">
</audio>
</section>
<section id="down-text"></section>