我要实现的功能就如掘金发沸点一致,输入内容后可以通过快捷键进行发送,而不需要使用鼠标点击确认。
在mac平台上使用⌘ + Enter,其它平台使用Ctrl + Enter。
监听键盘事件
给document添加keydown事件。
const onQuickConfirm = e => {
// ...
}
document.addEventListener('keydown', onQuickConfirm);
系统判断
通过navigator.platform来进行判断。
function getOs() {
const { platform } = navigator;
if (platform.startsWith('Mac')) return 'Mac';
if (platform.startsWith('Win')) return 'Win';
return '';
}
遗憾的是该api已被废弃,所以还是谨慎使用。
使用navigator.userAgent,参考current-device库
function getOs() {
const userAgent = navigator.userAgent.toLowerCase();
if (userAgent.includes('mac')) return 'Mac';
if (userAgent.includes('windows')) return 'Win';
// 其它
return '';
}
判断按键
const os = getOs();
if (os) {
const onQuickConfirm = e => {
// 是否按下Enter键
if (e.keyCode !== 'Enter') return;
// Mac系统 按下Enter键前按住了⌘
if ((os === 'Mac' && e.metaKey) || (os === 'Win' && e.ctrlKey)) {
onConfirm();
}
}
}