javascript – 按下某个键时播放声音

栏目: JavaScript · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/12578379/play-a-sound-when-a-key-is-pressed
有没有人知道是否有任何预定义的方法来为从键盘输入到 HTML

表单的每个字母播放声音?

例如:如果我输入Y,则在文本字段中,网站显示Y等.

或者,最好的方法是什么?

它很容易播放声音,并且很容易为按键添加处理程序,但是没有预定义的方法来链接这两个操作,因此您必须键入自己的代码.

1)按键操作

document.onkeydown = function() {
    ...

2)播放声音

添加音频元素:

<audio id=alarm>
    <source src=sound/zbluejay.wav>
</audio>

并执行它

document.getElementById('alarm').play();

例如,您可以构建一个将键码链接到声音元素ID的地图:

var sounds = {
   88 : 'alarm', // key 'x'
   ...

};
document.onkeydown = function(e) {
    var soundId = sounds[e.keyCode];
    if (soundId) document.getElementById(soundId).play();
    else console.log("key not mapped : code is", e.keyCode);
}

Yoy可能会找到密钥代码 here

翻译自:https://stackoverflow.com/questions/12578379/play-a-sound-when-a-key-is-pressed


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Development Recipes

Web Development Recipes

Brian P. Hogan、Chris Warren、Mike Weber、Chris Johnson、Aaron Godin / Pragmatic Bookshelf / 2012-1-22 / USD 35.00

You'll see a full spectrum of cutting-edge web development techniques, from UI and eye candy recipes to solutions for data analysis, testing, and web hosting. Make buttons and content stand out with s......一起来看看 《Web Development Recipes》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具