admin管理员组

文章数量:1326626

I am trying to mimic key press events, for instance Ctrl+D on a button click.

It would be great if someone can point me in the right direction on how to achieve the same.

I am trying to mimic key press events, for instance Ctrl+D on a button click.

It would be great if someone can point me in the right direction on how to achieve the same.

Share Improve this question edited Oct 8, 2010 at 22:17 Marcel Korpel 21.8k6 gold badges62 silver badges80 bronze badges asked Oct 8, 2010 at 21:59 SandhurstSandhurst 2372 gold badges6 silver badges11 bronze badges 1
  • 3 Is your question really about mimicking the keypress, or is the actual goal to trigger "Add Bookmark" functionality in browsers? (Hint: My browser doesn't have any feature bound to Ctrl+D). – Quentin Commented Oct 9, 2010 at 9:30
Add a ment  | 

4 Answers 4

Reset to default 1

You're not allowed to do that. Imagine all the havoc I could wreak if I could send CTRL-ALT-DEL at will.

The code for triggering a custom event (in this instance, Ctrl+d) is as follows:

var evt = jQuery.Event("keypress");
evt.keyCode = 100; // d
evt.ctrlKey = true;
$(document).trigger(evt);

NB that, as the other answers have said, this will be limited in its impact. You won't be able to affect normal browser functions in this way.

That would be "firing events", though I'm leaving the exercise to you to find the right code.

As the other guy said, you cannot do any kind of thing with it. It is purposefully limited.

However, let's say I have a wysiwyg editor in javascript, which supports receiving ctrl+s and saving, you should be able to fire that yourself and make it save anyway.

At the end, it's a matter of context (focus), and which sometimes fails (again, purposefully).

This will trigger ctrl+d

function btnClick(){
    document.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd', 'ctrlKey': true}));   
}

本文标签: javascriptExecute CtrlD on button clickStack Overflow