简体   繁体   English

如何获得聚合物组件内元素的实际事件keydown目标?

[英]How do I get the actual event keydown target of an element inside a polymer component?

The code to prevent backspace from navigating back usually takes something like this approach , where the window keydown event is blocked for backspace, except on a small set of known element types like Input, TextArea, and so on. 防止退格导航回来的代码通常采用类似这种方法的方法 ,其中窗口keydown事件被阻止退格,除了一小组已知的元素类型,如Input,TextArea等。

This doesn't quite work for elements inside polymer custom elements, because the keydown event target type is the type of the custom element, not the actual element that got the keydown. 这对聚合物自定义元素中的元素不起作用,因为keydown事件目标类型是自定义元素的类型,而不是获得keydown的实际元素。 Each custom element's type is different. 每个自定义元素的类型都不同。 This makes blocking backspace by target element type untenable. 这使得目标元素类型的阻塞退格无法维持。

Is there a way to know the type of the actual element, within the polymer element, that got the keypress? 有没有办法知道聚合物元素中获得按键的实际元素的类型? Or is there a better way altogether? 或者有更好的方法吗?

Whenever possible, it's good to try to engineer your project to avoid breaking encapsulation. 只要有可能,尝试设计项目以避免破坏封装是很好的。 This is the reason the event.target is adjusted when you cross shadow boundaries. 这是跨越阴影边界时调整event.target的原因。

However, the event.path property is an escape-hatch that contains an array of all the elements that have seen the event and should allow you to solve this problem. 但是, event.path属性是一个escape-hatch,它包含已经看过事件的所有元素的数组,并且应该允许您解决此问题。

One way is to dig down into the custom element's shadowdom (and it's shadowdom), to get the true active element. 一种方法是深入挖掘自定义元素的阴影(以及它的阴影),以获得真正的活动元素。 Something like this works on Chromium 36: 这样的东西适用于Chromium 36:

function getActiveElem(target) {    
  do {
    if (target.shadowRoot != null)  {      
      target = target.shadowRoot.activeElement;
    }
  } while(target.shadowRoot != null);
  return target;
}

window.addEventListener("keydown", function(e) {
  if (e.keyCode == 8) {     
    var preventKeyDown;

    var d = getActiveElem(e.target);  // Get the real active element

    switch (d.tagName.toUpperCase()) {
      case 'INPUT':
        // more smarts here
        preventKeyDown = false;
        break;         
      // case TEXTAREA, et al.
    }
    // e.preventDefault() if preventKeyDown        
  }
}

事件中获取元素:DIV,INPUT,TEXTAREA ......

e.target.nodeName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM