default
menu home
Icon library Sign up Login favorite_border message help_outline
Online notes - online bookmark

javascript捕获缺省的组合快捷键,比如CTRL+F

styleTags: All CSS html javascript php/other IT
by: fanshome  2023-06-09 06:22(UTC)

Demo

有时候我们需要在网页上捕获用户的按键动作,然后避免执行缺省动作,替换成我们想要执行的程序。

下面我们以拦截并接管“ctrl+f”组合键为例,代码如下:

CSScontent_copyCopy codes
body{background:#fcc;}
h1,h2{text-align:center;}
htmlcontent_copyCopy codes
<h1>鼠标先移动到红区点一下<br/>然后试试按下CTRL+F组合键</h1>
<br/><br/>
<h2>代码实际使用时无须先点击鼠标,此处只为实现演示需要。</h2>
javascriptcontent_copyCopy codes
document.addEventListener("keydown",(e)=>{
	const keyName = e.key;
	if (e.ctrlKey && (keyName=='f' || keyName=='F')) {
		e.preventDefault();
		alert('CTRL+F pressed.')
	}
}, false);

visibility 783


- for heavy web user Online notes
adimg
logo Post a comment

captcha
Please check the captcha code
Cancel