2012-04-10 176 views
7

我不是原生HTML程序員,所以請不要跳過我這個簡單的問題。當圖片被點擊時播放聲音文件

我有,我用下面的代碼顯示圖像:

<img name="track1" src="images/track1.png" width="180" height="180" border="0" id="track1" alt="" /> 

我想在單擊圖像時要播放的聲音文件。我可以使圖像成爲一個按鈕,但由於某種原因,這會讓頁面的佈局變得糟糕。

我可以使用任何球員,但唯一的是我不想顯示一個侵入球員。我只想讓用戶按下圖像並聽到音樂。如果他按下另一張圖像,則當前音樂需要停止播放,並且必須播放不同的聲音。

請幫忙!謝謝!

+0

您可以使用[HTML5音頻標籤(http://www.w3schools.com/html5/tag_audio.asp)和使用JavaScript啓動它後點擊 – Neysor 2012-04-10 06:11:03

+0

可能的重複:http://stackoverflow.com/questions/8489710/how-can-i-play-sound-in-jquery-when-click-a-button – Victor 2012-04-10 06:12:08

回答

5

首先你必須使用jQuery。 例如,你可以在你的頁面中創建一些<div>

<div id="wrap">&nbsp;</div>

然後,在你的JavaScript,當你要播放的文件,只需添加

$('#wrap').append('<embed id="embed_player" src="audio.wav" autostart="true" hidden="true"></embed>'); 

整個代碼看起來是這樣;

<script type="text/javascript" src="jquery-1.7.1.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
$('#track1').click(function(){ 
    $('#wrap').append('<embed id="embed_player" src="audio.wav" autostart="true" hidden="true"></embed>'); 
}); 
}); 
</script> 
<img name="track1" src="images/track1.png" width="180" height="180" border="0" id="track1" alt="" /> 
<div id="wrap">&nbsp;</div> 

希望這會有所幫助。

+0

我喜歡這個解決方案離子,但是JavaScript標籤描述說「除非另外包含框架/庫的另一個標籤,否則預計會有純JavaScript的答案。」也許這對於純JavaScript的答案是一個很好的補充。 – setholopolus 2017-11-28 03:44:55

0
<html>  
    <body> 
     <div id="container"> 
      <img name="track1" src="images/track1.png" width="180" height="180" border="0" id="track1" alt="" class="play" /> 
     </div> 
    </body> 
</html> 


<script> 
     $(document).ready(function() { 
      var audioElement = document.createElement('audio'); 
      audioElement.setAttribute('src', 'audio.mp3'); 
      audioElement.setAttribute('autoplay', 'autoplay'); 
      //audioElement.load() 

      $.get(); 

      audioElement.addEventListener("load", function() { 
       audioElement.play(); 
      }, true); 

      $('.play').click(function() { 
       audioElement.play(); 
      }); 

      $('.pause').click(function() { 
       audioElement.pause(); 
      }); 
     }); 
    </script> 
5

此答案由https://stackoverflow.com/a/7620930/1459653 @klaustopher(https://stackoverflow.com/users/767272/klaustopher)幫助了我。他寫道:

HTML5 has the new <audio>-Tag that can be used to play sound. It even has a pretty simple JavaScript Interface: 

`<audio id="sound1" src="yoursound.mp3" preload="auto"></audio> 
    <button onclick="document.getElementById('sound1').play();">Play 
    it</button>` 

這裏是我是如何實現自己的意見,使點擊字體真棒圖標「FA-音量增加」導致「donkey2.mp3」(後位於Web頁上的「騾子」。)播放聲音(注:MP3並不適用於所有的瀏覽器玩):

<p>In short, you're treated like a whole person, instead of a rented mule. <audio id="sound1" src="assets/donkey2.mp3" preload="auto"></audio><a class="icon fa-volume-up" onclick="document.getElementById('sound1').play();"></a>

相關問題