0

I have the code to launch an event when pressing a key.

$(document).keydown(function(e){
    if (e.keyCode == 37) { 
       alert( "left pressed" );
       return false;
    }
});

I was wondering how can I launch a sound

in my html I have this :

<audio id="sound1" src="images/step-1/iphone.mp3"></audio>
<audio id="sound2" src="images/step-1/iphone.mp3"></audio>

<div id="pad">

    <img src="images/step-1/tsonga.jpg" onclick="document.getElementById('sound1').play()"/>
    <img src="images/step-1/federer.jpg" onclick="document.getElementById('sound1').play()"/>

</div>

Like this, but it doesn't work :/

$(document).keydown(function(e){
    if (e.keyCode == 37) { 
       getElementById('sound1').play()
       return false;
    }
});

Thank you for your help !

4

2 回答 2

1

来自 W3Schools:

    <audio id="sound" controls>
      <source src="horse.mp3" type="audio/mpeg">
      <source src="horse.ogg" type="audio/ogg">
      Your browser does not support this audio format.
    </audio>

然后:

document.getElementById('sound').play();
于 2013-06-04T09:27:44.653 回答
0

尝试这个:

$(document).keydown(function(e){
    if (e.keyCode == 37) { 
       document.getElementById('sound1').play();
       return false;
    }
});

我认为你必须使用document.getElementById,因为如果你只写 getElementById 范围是窗口。

于 2013-06-04T09:27:09.587 回答