jQuery 触发 keyCode Ctrl+Shift+z +z +在所见即所得文本区域中按 Ctrl+z

发布于 2024-12-09 19:41:58 字数 95 浏览 0 评论 0原文

我想知道如何触发由 Ctrl+z 组成的事件 keyCode 和由 Ctrl+Shift+z 组成的事件 keyCode ?

i was wondering how do i trigger the event keyCode composed by Ctrl+z and the event keycode composed by Ctrl+Shift+z ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风吹短裙飘 2024-12-16 19:41:58

使用已通过 jquery 跨浏览器标准化的 e.which

$(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'); 
      }          
}); 

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'); 
      }          
}); 
眼波传意 2024-12-16 19:41:58

如果你想触发该事件,那么它应该是这样的:

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);

查看 JSBIN 链接

但似乎不起作用。我没有更多的时间花在这上面,但是,这是一个安全问题。我会在 MSDN 上看到这些文档, W3CMDN 看看是否有真正的方法可以做到这一点。

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.

哑剧 2024-12-16 19:41:58

Ctrl 和 Shift 键包含在按键事件中,但按键代码会引用您按下的键。 Ctrl 和 Shift 是控制键,它们在按键事件中拥有自己的键。

例如,如果您按 Ctrl+Shift+Z ,那么 keydown 事件将是这样的:

{
    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
}

如您所见,有两个键分别用于 CtrlShift键为 true,因为这些键是在按下 Z 时按下的。

因此,您可以像这样检测此事件:

document.addEventListener('keydown', function(event){
  if(event.keyCode == 90 && event.ctrlKey && event.shiftKey){
   // do your stuff
  }
}, false);

注意:您应该监听 keydown 以获得多个键盘快捷键。 keyup 不起作用。

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.

小镇女孩 2024-12-16 19:41:58

上面的答案很好并且有效,但是对于更动态的解决方案会有所帮助的情况,我有一个使用的替代解决方案。认识到我有点晚了,这是我的解决方案:

一个用于查看效果的 HTML 元素:

<span id="span"></span>

以及脚本:

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";})

这是一个高度缩写的版本,当我知道我是唯一一个会使用它的人时,我会使用它需要通读剧本。如果您认为其他人需要阅读和理解它,我建议使用稍微不同的脚本版本:

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];}
}

以下是这种方法的优点:

1)处理您的代码的其他人不需要知道任何你写的 JavaScript 可以工作。您可以让他们在需要时添加和删除命令。

2)可以动态添加命令(可能取决于用户输入)。

3 ) 非常复杂的按键命令、重载命令和其他更复杂的操作对于其他解决方案可能会更困难。

下面测试一下:

    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>

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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文