我有一些代码,如果您按键盘上的W会播放声音。
document.addEventListener("keydown", function(event) {
if (event.keyCode == 87) {
event.preventDefault();
sound.currentTime = 0;
sound.play()
} else {
return false;
}
})
function playSound() {
sound.currentTime = 0;
sound.play()
}
.whitebg {
background-color: white;
color: black;
transition: 1.5s;
border: 1px solid black;
}
.whitebg:hover {
background-color: #555555;
transition: 0.4s;
color: white;
}
<div class="whitebg key" onclick="playSound()">click or press W to play</div>
如您所见,当您将鼠标悬停在DIV上时,它将在0.4秒内转换为具有灰色背景和白色文本,并在1.5秒内转换回。
我希望W的按键与鼠标悬停具有相同的结果。 请回答使用纯JavaScript,而不是jQuery或其他内容。
答案 0 :(得分:0)
您可以修改CSS以将样式应用于元素时悬停的元素,或也具有类active
的元素。然后在您的keydown事件中,只需将该类添加到按钮中即可。
根据Ted在下面的评论中的建议,我添加了一个计时器,该计时器也将在500毫秒后删除高亮显示。
document.addEventListener("keydown", function(event) {
if (event.keyCode !== 87) return;
event.preventDefault();
flashPlayButton(500);
});
function flashPlayButton(ms) {
var playButton = document.getElementById("play");
playButton.classList.add("active");
setTimeout(function() {
playButton.classList.remove("active");
}, ms);
}
.whitebg {
background-color: white;
color: black;
transition: 1.5s;
border: 1px solid black;
}
.whitebg:hover, .whitebg.active {
background-color: #555555;
transition: 0.4s;
color: white;
}
<div id="play" class="whitebg key" onclick="playSound()">click or press W to play</div>
答案 1 :(得分:0)
您可以在按下W时将一个名为blackbg的css类添加到div,然后在不再按下W时将其删除。
var whiteBg = document.querySelector('.whitebg');
document.addEventListener("keydown", function(event) {
if (event.keyCode == 87) {
event.preventDefault();
whiteBg.classList.add("blackbg");
sound.currentTime = 0;
soundE.play()
} else {
return false;
}
})
function playSound() {
sound.currentTime = 0;
sound.play()
}
document.addEventListener("keyup", function(event) {
if (event.keyCode == 87) {
event.preventDefault();
whiteBg.classList.remove("blackbg");
}
});
.whitebg {
background-color: white;
color: black;
transition: 1.5s;
border: 1px solid black;
}
.blackbg,
.whitebg:hover {
background-color: #555555;
transition: 0.4s;
color: white;
}
<div class="whitebg key" onclick="playSound()">click or press W to play</div>
答案 2 :(得分:0)
也许像这样可以解决问题: 1.按下W键时,它将为元素添加一个类 2.释放W键时,它将从元素中删除该类 所以这样的事情可能会解决问题:
const bg = document.querySelector(".whitebg");
document.body.addEventListener("keypress", (e)=>{
// Key code 87 refers to W key
if(e.keyCode == 87) {
whitebg.classList.add("active");
}
})
document.body.addEventListener("keyup", (e)=>{
// Removes the class "active" as soon as you release the key.
whitebg.classList.remove("active");
})
希望这可以解决问题,尽管没有两个事件侦听器的实现方法可能更短。