【问题标题】:Play an audio file when click is inside image and a different audio file when click is outside image当点击在图像内时播放音频文件,当点击在图像外时播放不同的音频文件
【发布时间】:2017-08-08 21:27:52
【问题描述】:

我正在通过自己做一些小练习来学习 HTML-CSS-JS。我创建了一个小代码,当我单击图像时播放 mp3 音频:

 <html>
  <head>
    <title>Image audio exercise</title>
  </head>
  <body>
    <script>
      function play(){
         var audio = document.getElementById("audio");
         audio.play();
      }
    </script>
    <img src="img.gif" onclick="play()">
    <audio id="audio" src="sound.mp3" ></audio>
  </body>
 </html> 

当点击在图像之外时,我希望能够播放不同的音频文件。有没有简单的方法来做到这一点?也许是 if-else 语句?

【问题讨论】:

标签: javascript html image audio onclick


【解决方案1】:

做这样的事情:

document.onclick = function(e) {
if (e.target != document.getElementById('clickMe')) {
    document.getElementById('audio').play();
}else {
    document.getElementById('audio2').play();
}

}

【讨论】:

    【解决方案2】:

    你可以做这样的事情。只需简单检查一下您是否单击了图像或文档。

    <html>
      <head>
        <title>Image audio exercise</title>
      </head>
      <body>
    
        <img id="theImage" src="img.gif">
        <audio id="audio" src="sound.mp3" ></audio>
    
        <script>
          var audio = document.getElementById("audio");
          var img = document.getElementById("theImage");
    
          document.addEventListener("click", function(e){
             if( e.target === img ){
               audio.src = "sound.mp3";
               audio.play();
             }
             else{
               audio.src = "sound2.mp3";
               audio.play();
             }
          },false);
        </script>
    
      </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 2021-08-03
      • 2013-09-20
      • 1970-01-01
      相关资源
      最近更新 更多