javascript 所见即所得文本区域中的 jQuery 触发器 keyCode Ctrl+Shift+z & Ctrl+z

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7747536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:10:00  来源:igfitidea点击:

jQuery Trigger keyCode Ctrl+Shift+z & Ctrl+z in wysiwyg textarea

javascriptjquerytriggerswysiwygkeycode

提问by itsme

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

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

采纳答案by Mohsen

If you want to trigger the event then it should be something like this:

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

HTML

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

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

查看JSBIN链接

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, W3Cand MDNto see if there is a real way to do this.

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

回答by aziz punjani

Use e.whichwhich has been normalized cross browser by jquery.

使用e.which已被 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'); 
      }          
}); 

回答by Mohsen

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.

Ctrl 和 Shift 键包含在键事件中,但键码决定您按下哪个键。Ctrl 和 Shift 是控制键,它们在键事件中有自己的键。

For example if you press Ctrl+Shift+Zthen keydown event would be this:

例如,如果您按下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
}

As you can see there is two key for Ctrland Shiftkeys that are true because those keys were pressed while pressing Z.

正如您所看到的,有两个键 forCtrlShift键是真的,因为在按下 的同时按下了这些键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 keydownfor multiple key keyboard shortcuts. keyupwouldn't work.

注意:您应该监听keydown多个键盘快捷键。keyup行不通。

回答by eardstapa

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:

用于查看效果的 HTML 元素:

<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.

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

2 ) Commands can be added dynamically (possibly depending on user input).

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

3 ) Very complex key commands, overloaded commands and other more complex operations might be more difficult with other solutions.

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

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>