admin管理员组

文章数量:1392073

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.

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

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.

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

Share Improve this question edited May 23, 2017 at 11:49 CommunityBot 11 silver badge asked Sep 13, 2014 at 20:00 Ed EvansEd Evans 1781 silver badge7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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.

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.

Get element from event: DIV, INPUT, TEXTAREA ...

e.target.nodeName

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:

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

本文标签: