我有一些div,我使用jQuery的淡入/淡出来点击链接时进入页面。每个页面都有一个关联的html5音频元素,它也相应地淡入/淡出。
$('.link').on('click', function(e){
var targetpage = $($(this).attr("href"));
$('.pagecontainer>div').fadeOut(0); //fade out currently displayed page
targetpage.fadeIn(); //fade in page associated with link
if (targetpage.children().hasClass('backgroundmusic')) {
$('audio').animate({volume: 0}, 1000); //fade out currently playing audio
alert('audio faded out');
$.each($('audio'), function () { //stop all audio
this.currentTime=0;
this.pause();
alert('audio stopped');
});
alert('stop function executed');
}
});
$('.sound').on('play', function () { //since volume was faded out, reset volume when click play button
$('audio').animate({volume: 1}, 100);
});
HTML:
<a href="#page1" class="link">Audio 1</a>
<a href="#page2" class="link">Audio 2</a>
<a href="#page3" class="link">Audio 3</a>
<div class="pagecontainer">
<div id="page1"> //all three audio elements are in exact same spot
//clicking page link fades in current audio and fades in new one
<div class="backgroundmusic">
<audio controls loop class="sound" preload="none">
<source src="../../site/music/music1.mp3"/>
<source src="../../site/music/music1.ogg"/>
</audio>
</div>
</div>
<div id="page2">
<div class="backgroundmusic">
<audio controls loop class="sound" preload="none">
<source src="../../site/music/music2.mp3"/>
<source src="../../site/music/music2.ogg"/>
</audio>
</div>
</div>
<div id="page3">
<div class="backgroundmusic">
<audio controls loop class="sound" preload="none">
<source src="../../site/music/music3.mp3"/>
<source src="../../site/music/music3.ogg"/>
</audio>
</div>
</div>
</div>
“警报('音频消失')”将执行,但“警报('音频停止')”不执行,因为它没有运行“$ .each($( 'audio'),功能“脚本完全没有”,警报('停止功能执行')“。我必须将这个”每个“脚本用作$('audio')。currentTime = 0不起作用,也不起作用$('audio')。pause(),因为我的页面上有多个音频实例。
有谁知道为什么这不起作用?
感谢。
答案 0 :(得分:1)
您将e
传递给您的函数但不使用它。可能希望阻止该点击事件的默认操作。
e.preventDefault(); //Put this at the top of the callback
这应该可以修复你的.each()问题。此外,您应该使用控制台而不是警报,以免冻结您的页面。
console.log('audio faded out'); //Use console instead of alerts
$('audio').each(function () { //Do it this way.
this.currentTime=0;
this.pause();
console.log('audio stopped');
});
console.log('stop function executed');