【问题标题】:How to detect whether shift was pressed during onclick handler?如何检测在 onclick 处理程序期间是否按下了 shift?
【发布时间】:2017-11-22 19:18:22
【问题描述】:

我有处理程序:

myObj[id] = new google.maps.Circle({/*Initialization*/}
myObj[id].addListener('click', function (event) {
     //Some code here
 myFunction(this, event);
}

还有那个不起作用的功能。

myFunction(elem, event) {
    console.log(event);
    if(!event.shiftKey) { //Do Something }
}    

从下图中可以看出,qZ 对象有Aa 属性? 是负责MouseEvents 的,对吧?

好吧,如果我将函数更改为:

myFunction(elem, event) {
    if(!event.Aa.shiftKey) { //Do Something }
}  

它有效。问题是,这个Aa 在此之前曾经是VaXa。我不能一直改变。我不知道为什么会发生这种情况,也不知道如何解决。

检测到click 正常调用函数,但是忽略了shiftKey。我如何在click 事件中检测到shiftKey

更新:

按照 Dan 给出的提示,我尝试循环遍历对象并尝试找到 shiftKey

var shiftKey;
      if (Object.keys(event).some(function (key) {
            if (event[key] && 'shiftKey' in event[key]) {
                  shiftKey = event[key].shiftKey;
                  return true;
            }
            return false;
      })) {
            // We found it, `shiftKey` has the value. Do nothing
      } else {
            //If no shiftKey is pressed execute my code!
      }

但是现在它永远不会执行我应该在不按下 shiftKey 时触发的代码...

【问题讨论】:

  • addListener是什么框架?
  • 对不起,我想我不太明白你的问题。不使用任何框架。它检测到点击但忽略 shiftKey。
  • 我希望addEventListener 不是addListener。我不确定你从哪里得到addListener
  • @epascarello 我的错!用更多信息更新了问题。

标签: javascript jquery dom-events


【解决方案1】:

从您的更新中我看到了一个错误:

var shiftKey;
      if (Object.keys(event).some(function (key) {
            if (event[key] && 'shiftKey' in event[key]) {
                  shiftKey = event[key].shiftKey;
                  return true; // <- should be return shiftKey
            }
            return false;
      })) {
            // We found it, `shiftKey` has the value. Do nothing
      } else {
            //If no shiftKey is pressed execute my code!
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多