问题
i was wondering how do i trigger the event keyCode composed by Ctrl+z
and the event keycode composed by Ctrl+Shift+z
?
回答1:
If you want to trigger the event then it should be something like this:
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type=button value=CTRL+SHIFT+Z id=bcsz />
<input type=button value=CTRL+Z id=bcz />
<textarea id=t ></textarea>
</body>
</html>
JavaScript
var t = document.getElementById('t'), //textarea
bcsz = document.getElementById('bcsz'), //button ctrl shift z
bsz = document.getElementById('bcz'), // button ctrl z
csz = document.createEvent('KeyboardEvents'), //ctrl shift z event
cz = document.createEvent('KeyboardEvents'); // ctrl z event
csz.initKeyboardEvent(
'keydown',
true, // key down events bubble
true, // and they can be cancelled
document.defaultView, // Use the default view
true, // ctrl
false, // alt
true, //shift
false, //meta key
90, // keycode
0
);
cz.initKeyboardEvent(
'keydown',
true, // key down events bubble
true, // and they can be cancelled
document.defaultView, // Use the default view
true, // ctrl
false, // alt
false, //shift
false, //meta key
90, // keycode
0
);
bcz.addEventListener('click', function(){
t.dispatchEvent(cz);
}, false);
bcsz.addEventListener('click', function(){
t.dispatchEvent(csz);
}, false);
LOOK AT JSBIN LINK
But it seems it doesn't works. I don't have more time to spend on this, but yeah this is kind of a security issue. I would see these docs at MSDN, W3C and MDN to see if there is a real way to do this.
回答2:
Use e.which
which has been normalized cross browser by jquery.
$(document).keydown(function(e){
if( e.which === 90 && e.ctrlKey && e.shiftKey ){
console.log('control + shift + z');
}
else if( e.which === 90 && e.ctrlKey ){
console.log('control + z');
}
});
回答3:
Ctrl and Shift keys are included in key events but keycode is refereeing to which key you press. Ctrl and Shift are control keys and they have their own keys in key events.
For example if you press Ctrl+Shift+Z
then keydown event would be this:
{
altGraphKey: false
altKey: false
bubbles: true
cancelBubble: false
cancelable: true
charCode: 0
clipboardData: undefined
ctrlKey: true
currentTarget: null
defaultPrevented: true
detail: 0
eventPhase: 0
keyCode: 90
keyIdentifier: "U+004C"
keyLocation: 0
layerX: 0
layerY: 0
metaKey: false
pageX: 0
pageY: 0
returnValue: false
shiftKey: true
srcElement: HTMLTextAreaElement
target: HTMLTextAreaElement
timeStamp: 1318460678544
type: "keydown"
view: DOMWindow
which: 90
__proto__: KeyboardEvent
}
As you can see there is two key for Ctrl
and Shift
keys that are true because those keys were pressed while pressing Z
.
So you can detect this event like this:
document.addEventListener('keydown', function(event){
if(event.keyCode == 90 && event.ctrlKey && event.shiftKey){
// do your stuff
}
}, false);
Note: You should listen to keydown
for multiple key keyboard shortcuts. keyup
wouldn't work.
回答4:
The answers above are good and work, but for situations where a more dynamic solution would be helpful I have an alternate solution that I use. Recognizing that I'm a little late to the game, this is my solution:
An HTML element to view the effects in:
<span id="span"></span>
And the script:
function Commands()
{
var k = [], c = {}, b = false;
var l = l => l.key.toLowerCase();
var inside = (e) => k.includes(l(e));
var put = (e) => k.push(l(e));
var pull = (e) => { k.splice(k.indexOf(l(e)), 1) };
var add = (e) => { if (!inside(e)) put(e); return 1; };
var also = (p, i) => k.includes(c[p].combination[i].toLowerCase());
var set = () => { b = true; return 1; };
var all = (p) => { var d = true; for (var i = 0; i < c[p].combination.length; i++) d = d && also(p, i); return d; }
var found = (p) => { set(); all(p); };
window.addEventListener("keydown", (e) => { add(e); for (var p in c) if (all(p)) c[p].action(); return 1; });
window.addEventListener("keyup", (e) => { pull(e) });
this.setCommand = (n, h, f) => { c[n] = { combination : h, action : f }; return 1; };
this.getCommands = () => c;
this.getKeys = () => k;
this.clearCommands = () => { c = {}; return 1; };
this.removeCommand = (n) => { return delete c[n];}
}
var commands = new Commands();
commands.setCommand("save", ["control", "shift", "z"], function(){document.getElementById("span").innerHTML = "saved";})
commands.setCommand("close", ["alt", "c"], function(){document.getElementById("span").innerHTML = "closed";})
This is a highly abbreviated version that I use when I know that I am the only one who will need to read through the script. If you think someone else will need to read and understand it, I would suggest using a slightly different version of the script:
function Commands()
{
var keys = [];
var combinations = {
save : {
combination : ["alt", "s"],
action : function(){ window.alert("here"); return 1; }
}
}
window.addEventListener("keydown", function(e){
if (!keys.includes(e.key.toLowerCase()))
{
keys.push(e.key.toLowerCase());
}
for (var p in combinations)
{
var allDown = true;
for (var i = 0; i < combinations[p].combination.length; i++)
{
allDown = allDown && keys.includes(combinations[p].combination[i].toLowerCase());
}
if (allDown)
{
combinations[p].action();
}
}
return 1;
})
window.addEventListener("keyup", function(e){
while (keys.indexOf(e.key.toLowerCase()) != -1)
{
keys.splice(keys.indexOf(e.key.toLowerCase()), 1);
}
return 1;
})
this.setCommand = (n, h, f) => { combinations[n] = { combination : h, action : f }; return 1; };
this.getCommands = () => combinations;
this.getKeys = () => keys;
this.clearCommands = () => { combinations = {}; return 1; };
this.removeCommand = (n) => { return delete combinations[n];}
}
Here are the advantages of this approach:
1 ) Someone else working on your code does not need to know how any of the JavaScript you wrote works. You can just have them add and remove commands whenever they need to.
2 ) Commands can be added dynamically (possibly depending on user input).
3 ) Very complex key commands, overloaded commands and other more complex operations might be more difficult with other solutions.
Test it out below:
function Commands()
{
var k = [], c = {}, b = false;
var l = l => l.key.toLowerCase();
var inside = (e) => k.includes(l(e));
var put = (e) => k.push(l(e));
var pull = (e) => { k.splice(k.indexOf(l(e)), 1) };
var add = (e) => { if (!inside(e)) put(e); return 1; };
var also = (p, i) => k.includes(c[p].combination[i].toLowerCase());
var set = () => { b = true; return 1; };
var all = (p) => { var d = true; for (var i = 0; i < c[p].combination.length; i++) d = d && also(p, i); return d; }
var found = (p) => { set(); all(p); };
window.addEventListener("keydown", (e) => { add(e); for (var p in c) if (all(p)) c[p].action(); return 1; });
window.addEventListener("keyup", (e) => { pull(e) });
this.setCommand = (n, h, f) => { c[n] = { combination : h, action : f }; return 1; };
this.getCommands = () => c;
this.getKeys = () => k;
this.clearCommands = () => { c = {}; return 1; };
this.removeCommand = (n) => { return delete c[n];}
}
var commands = new Commands();
commands.setCommand("save", ["control", "shift", "z"], function(){document.getElementById("span").innerHTML = "saved";})
commands.setCommand("close", ["alt", "c"], function(){document.getElementById("span").innerHTML = "closed";})
#span {
font-size : 25px;
font-family : Palatino;
color : #006622;
}
<span id="span"></span>
来源:https://stackoverflow.com/questions/7747536/jquery-trigger-keycode-ctrlshiftz-ctrlz-in-wysiwyg-textarea