jQuery Trigger keyCode Ctrl + Shift + z&在wysiwyg textarea中按Ctrl + z

时间:2011-10-12 22:56:22

标签: javascript jquery triggers wysiwyg keycode

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

4 个答案:

答案 0 :(得分:10)

使用已通过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'); 
      }          
}); 

答案 1 :(得分:5)

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

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

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

答案 2 :(得分:3)

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个键有两个键是真的,因为在按Z时按下了这些键。

所以你可以像这样检测这个事件:

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

注意:您应该听keydown多个键盘快捷键。 keyup无效。

答案 3 :(得分:0)

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

用于查看效果的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>