简体   繁体   English

CTRL + C 和关键字键 C,两个事件同时工作 JavaScript || Jquery

[英]CTRL + C and keyword key C , both events work at same time JavaScript || Jquery

As i am creating keyword shortcut to my website, like by pressing C key, it redirects me to any page I want.当我正在为我的网站创建关键字快捷方式时,例如按C键,它会将我重定向到我想要的任何页面。

But the problem occur that when I press Ctrl+C combination, it copies text for me, but it also redirects me to other page.但是问题是当我按下Ctrl+C组合时,它会为我复制文本,但它也会将我重定向到其他页面。

I tried to create a small demo:我试图创建一个小演示:

 document.onkeyup = function(e) { var e = e || window.event; if ((e.which == 67)) { alert("C key is pressed"); }else if ((e.ctrlKey) && (e.which == 67)) { alert("Text Copied"); } };
 body { background-color: #fff; } h5{ text-align:center; font-size:20px; font-weigt:bold; }
 <h5>Creating Shortcut for Website</h5> <p>By clicking on <q>C</q> key on Keyboard, your page will reload</p>

Hope you will understand.希望你能理解。

Thanks for you attendance.谢谢你的出席。

Change your code such that checking for Ctrl + C come before checking for the redirection key.更改您的代码,以便在检查重定向键之前检查Ctrl + C

Also, note that KeyboardEvent#which is deprecated, so you should use KeyboardEvent#key instead:另外,请注意KeyboardEvent#which已被弃用,因此您应该改用KeyboardEvent#key

 document.onkeyup = function(e) { e = e || window.event; if (e.ctrlKey && e.key === 'c') { alert("Text copied"); }else if (e.key === 'c') { alert("C key is pressed"); } };
 body { background-color: #fff; } h5{ text-align:center; font-size:20px; font-weigt:bold; }
 <h5>Creating Shortcut for Website</h5> <p>By clicking on <q>C</q> key on Keyboard, your page will reload</p>

However, that won't work always.但是,这并不总是有效。

If you do the following:如果您执行以下操作:

Ctrl down
C down
C up
Ctrl up

...then it will work, but if the sequence is (which would also trigger a copy operation): ...那么它会起作用,但如果序列是(这也会触发复制操作):

Ctrl down
C down
Ctrl up
C up

...then it won't. ……那就不行了。

Why?为什么?

The problem is the keyup event itself.问题在于keyup事件本身。 As the event object represents the keyboard state at the time when the event is emitted, keyup checks for modifier keys when C is released .由于事件 object 代表事件发出时的键盘 state,因此keyup释放C检查修饰键。

However, since modifier keys usually have to be pressed before the key they modify, checks should happen at the time when the keys are pressed down .但是,由于修饰键通常必须在它们修改的键之前被按下,所以检查应该在按下键的时候进行。

So, you'll have to use the keydown event instead:因此,您必须改用keydown事件:

 document.onkeydown = function(e) { e = e || window.event; if (e.ctrlKey && e.key === 'c') { alert("Text copied"); }else if (e.key === 'c') { alert("C key is pressed"); } };
 body { background-color: #fff; } h5{ text-align:center; font-size:20px; font-weigt:bold; }
 <h5>Creating Shortcut for Website</h5> <p>By clicking on <q>C</q> key on Keyboard, your page will reload</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM