gpt4 book ai didi

将 keyCodes 转换为字符的 JavaScript 函数

转载 作者:行者123 更新时间:2023-11-29 10:19:55 25 4
gpt4 key购买 nike

在任何 JavaScript 框架中是否有任何内置函数可以将 keyCodes 转换为字符?其中考虑了 shift 属性,因此它将返回正确的字符。

或者我们只需要构建自己的函数?

最佳答案

你可以使用 String.fromCharCode()

来自 MDN :

语法:String.fromCharCode(num1, ..., numN)

参数:num1, ..., numN(Unicode 值的数字序列。)

This method returns a string and not a String object.

Because fromCharCode is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.


更新:

在这里,我创建了一个函数来满足您的需求: http://jsbin.com/ukukuq/2/

(Code)

function keyDownEvent(e) {
var other = {};
var output= {};
output['meta'] = {};
var html = '';

e = (e) ? e : ((event) ? event : null);

if (e) {
output['keyCode'] = (e.keyCode) ? e.keyCode : 'N/A';
output['charCode'] = (e.charCode) ? e.charCode : 'N/A';
output['meta']['shift'] = e.shiftKey ? true : false;
output['meta']['ctrl'] = e.ctrlKey ? true : false;
output['meta']['alt'] = e.altKey ? true : false;
output['meta']['meta'] = e.metaKey ? true : false;

html = document.getElementById('output')
return html.innerHTML += '<pre>keyDown : ' + JSON.stringify(output) + '</pre>';
} else {
return 'error';
}
}

function keyPressEvent(e) {
var other = {};
var output= {};
var html = '';

e = (e) ? e : ((event) ? event : null);

if (e) {
output['keyCode'] = (e.keyCode) ? e.keyCode : 'N/A';
output['charCode'] = (e.charCode) ? e.charCode : 'N/A';

html = document.getElementById('output')
return html.innerHTML += '<pre>keyPress : ' + JSON.stringify(output) + ' Character : <strong>' + String.fromCharCode(output['charCode']) + '</strong></pre><hr/>';
} else {
return 'error';
}
}

var test = document.getElementById('test');
test.onkeydown = keyDownEvent;
test.onkeypress = keyPressEvent;

关于将 keyCodes 转换为字符的 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13992111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com