我正在制作一个音板页面,我让它播放音频并在点击图像时更改图像。但是,当我按下特定的keyCodes时,我也试图改变图像。
document.addEventListener('keydown', function(e) {
if (e.keyCode == 65) {
document.getElementById('myTune10').play();
}
});
这是图像更改的CSS。我在点击keyCode时尝试使用RightThereOhkaye.jpg图像。
button:active, .buttontwo:active {
background:url(images/RightDereOhkaye.jpg) no-repeat;
答案 0 :(得分:0)
尝试
document.getElementById(...).style.background = 'url(images/RightThereOhkaye.jpg) no-repeat';
将...替换为要更新图像的元素的ID
答案 1 :(得分:0)
注意:强>
keydown
仅跟踪密钥本身,而不是密钥的状态。
因此,如果您在键盘上按 a 键,KeyDown
生成Keys.A的KeyCode,如果按,则生成
shift + a 您还可以获得Keys.A的KeyCode。所以,
认识到之间的区别
shift + a 和 a ,你必须使用
keypress
代替keydown
。请参阅下面的代码段:
var player = document.getElementById( 'myTune10' ),
button = document.getElementById( 'button' );
/* Play / Pause when 'A' Key pressed */
document.addEventListener( 'keypress', function( e ) {
var char = e.which || e.keyCode;
if ( char == 65 ) button.click()
} )
/* Add click event to play button */
button.addEventListener( 'click', function() {
( player.paused ) ? player.play() : player.pause()
} )
/* Add class and change image when audio is playing */
player.addEventListener( 'play', function() {
button.classList.add( 'pause' )
} )
/* Remove class and change image when audio paused */
player.addEventListener( 'pause', function() {
button.classList.remove( 'pause' )
} )
/* Show contents when data for the current frame is available and loaded */
player.addEventListener( 'loadeddata', function() {
document.getElementById( 'player' ).style.display = 'block'
} )
#player {
display: none
}
.play {
width: 48px;
height: 40px;
border: 1px solid #ccc;
border-radius: 5px;
background: #eee url(https://www.w3.org/TR/WWWicn/play-start.gif) center center no-repeat
}
.pause {
background-image: url(https://www.w3.org/TR/WWWicn/play-pause.gif)
}
<div id="player">
<h2>Click here and press “A“ (Capital letter) to Play / Pause.</h2>
<button type="button" id="button" class="play"></button>
<audio id="myTune10">
<source src="https://freesound.org/data/previews/432/432256_4397472-lq.mp3" type="audio/mpeg">
</audio>
</div>