<!doctype html><html lang="en"><head><meta charset="UTF-8"></head><body></body><script>let longPressKey = {timeout: null,trigger(pressedEndCallback, //长按结束触发方法pressedStartCallback, //按下触发方法pressedUpCallback, //弹起触发方法key = 'Pause', //长按什么键delaySecond = 3 //长按多少秒触发) {onkeydown = (e) => {let k = e.keyCode || e.which || e.charCode,ck = e.ctrlKey || e.metaKey,ak = e.altKey,sk = e.shiftKey;if (e.key === key) {if (!this.timeout) {pressedStartCallback && pressedStartCallback(e);this.timeout = setTimeout(() => {this.timeout = null;pressedEndCallback && pressedEndCallback(e);}, 1000 * delaySecond);}}};onkeyup = (e) => {clearTimeout(this.timeout);this.timeout = null;pressedUpCallback && pressedUpCallback(e);};},};//测试用例----------------------------------------let versionTime = '2月6日 17:43:12';longPressKey.trigger((e) => {// 长按超时执行alert(`【更新时间】${versionTime}\n(注意校对是否已发布最新代码)`);},(e) => {// 刚刚按下键console.log("按键对象",e);},(e) => {// 弹起console.log("弹起键对象",e);},'Pause',3);</script></html>
原生js实现【longPressKey】长按键盘任意键(或组合键)3秒触发自定义事件(以Pause/Break键为例)
如果觉得《原生js实现【longPressKey】长按键盘任意键(或组合键)3秒触发自定义事件(以Pause/B》对你有帮助,请点赞、收藏,并留下你的观点哦!