如何在一个页面上使用多个音频的播放和暂停按钮?

时间:2014-11-04 06:52:30

标签: javascript jquery css html5 audio

使用Javascript:

<script>
/**
* jQuery document ready function (when the DOM is loaded)
* From here we can use $ to reference the jQuery object
*/
jQuery(document).ready(function($) {
/**
* Finds all elements that have _BOTH_ the .audio and .controls classes
* then attaches a click handler to the .playpausebtn class
*/
$('.audio.controls').on('click', '.playpausebtn', function(e) {
/**
* $(this) refers to the element that the event has fired on, in this case its the
* .playpausebtn that you clicked on (not any of the others)
*
* $(this).parent() will target the parent element, then inside the parent element we want to
* find the `audio` element
*
* Using the array key [0] should access the element directly, rather than the set of matched elements
*/
audio = $(this).parent().find('audio')[0];
if ( audio.paused ) {
audio.play();
$(this).css( 'background', 'url("Images/pause.png") no-repeat' );
} else {
audio.pause();
$(this).css( 'background', 'url("Images/play.png") no-repeat' );
}
});
});
</script>

HTML:

<div class="controls">
<audio class="audio" name="audio" src="Media/Beats/Catching waves/Catching Waves - [Prod. By Jordan Ace] - Preview Version.mp3"></audio>
<button class="playpausebtn"></button>
<button class="mutebtn"></button>
</div>
<div class="controls">
<audio class="audio" name="audio" src="Media/Beats/Coming up/Coming Up - [Prod. By Jordan Ace] - Preview Version.mp3"></audio>
<button class="playpausebtn"></button>
<button class="mutebtn"></button>
</div>

不幸的是我的音频根本没有播放,有人可以帮助我吗?我不知道我哪里出错了。它将用于在我的网站的一个页面上的表格中播放多个曲目。

1 个答案:

答案 0 :(得分:0)

您的初始选择器$('.audio.controls')错误。它应该是$('.controls')。这可能有所帮助。