2014-10-31 222 views
1

這裏是一個的jsfiddle:JavaScript的播放/暫停音頻切換

http://jsfiddle.net/8LczkwLz/19/

HTML:

<audio class="flashcardAudio" preload='none'> 
    <source src="http://dl.dropbox.com/u/1538714/article_resources/song.m4a" type='audio/mpeg' /> 
</audio> 

<a class="speakerClicked"> 
    <img src="http://codropspz.tympanus.netdna-cdn.com/codrops/wp-content/uploads/2010/01/play1-150x150.png"/> 
</a> 

JS:

var flashcardAudio = document.getElementsByClassName('flashcardAudio'), 
control = document.getElementsByClassName('speakerClicked'); 

control.onclick = function() { 
    pause_html='<img src="https://cdn2.iconfinder.com/data/icons/media-and-navigation-buttons- square/512/Button_4-128.png">'; 
    speaker_html='<img src="http://codropspz.tympanus.netdna-cdn.com/codrops/wp-content/uploads/2010/01/play1-150x150.png">'; 

    // Update the Button 
    var pause = control.innerHTML === pause_html; 
    control.innerHTML = pause ? speaker_html : pause_html; 

    // Update the Audio 
    var method = pause ? 'pause' : 'play'; 
    flashcardAudio[method](); 

    // Prevent Default Action 
    return false; 
}; 

上播放按鈕的點擊,我想看到它切換到暫停按鈕,反之亦然。似乎是在JS中輸入函數的問題,但由於警報消息從不觸發。

回答

1

你忘了針對特定的元素,僅僅通過更換您的JS line 1 and 2

var flashcardAudio = document.getElementsByClassName('flashcardAudio')[0], 
control = document.getElementsByClassName('speakerClicked')[0]; 

,並刪除在暫停按鈕IMG URL的空間。

查看jsfiddle

+0

謝謝,這個讓我瘋了!當SO允許時,我會接受答案。 – mtcrts70 2014-10-31 00:43:36

+0

不客氣;)在'暫停'按鈕URL中也有一個空格,我刪除它並且效果很好(更新[jsfiddle](http://jsfiddle.net/8LczkwLz/23/)) – lapin 2014-10-31 00:45:18

+0

再次感謝: )我必須查看定位 – mtcrts70 2014-10-31 00:53:49